Search code examples
pythonpandasdataframerow

Merge multiple column in one column in python


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}}

Solution

  • 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