Home > Net >  Merge multiple column in one column in python
Merge multiple column in one column in python

Time:12-16

I have a pandas data frame where the total of first column is done in second column and same for the second and third column:

    Column1  Column2  Column3  
 0     3                         
 1     2                         
 2     1       6                 
 3             7        13  

What I want to do now is merge all the columns (1,2,3) into one column A (ignoring the total value) like this:

     Column A      
 0      3                         
 1      2                         
 2      1                        
 3      7  

How could I best approach this issue? Here is the code mentioned below.

import pandas as pd
 
data = {'Column1':[3, 2, 1, ""],
        'Column2': ["", "", "6", "7"],
        'Column3':["", "", "", 13]}

abc = pd.DataFrame(data)

abc

abc.to_dict()

My Output:

{'Column1': {0: 3, 1: 2, 2: 1, 3: ''},
 'Column2': {0: '', 1: '', 2: '6', 3: '7'},
 'Column3': {0: '', 1: '', 2: '', 3: 13}}

CodePudding user response:

Replace to missing values empty strigs, then back filling missing values and select first column, last convert to integers if necessary and to one column DataFrame:

data = {'Column1':[3, 2, 1, ""],
        'Column2': ["", "", "6", "7"],
        'Column3':["", "", "", 13]}

df = pd.DataFrame(data)

df1 = df.replace('', np.nan).bfill(axis=1).iloc[:, 0].astype(int).to_frame('Column A')
print (df1)
   Column A
0         3
1         2
2         1
3         7

CodePudding user response:

You can create list across columns, remove empty spaces and take the first elements:

df['Column A'] = df.apply(lambda x: list(x), axis=1).apply(lambda x: [i for i in x if i!=''][0]).astype(int)

Output:

0    3
1    2
2    1
3    7
dtype: int64
  • Related