1

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}}
4
  • 2
    Are empty values NaN or empty string i.e ''? Please add df.to_dict() to the question. Commented Dec 16, 2021 at 5:50
  • The empty values are empty strings ' ' Commented Dec 16, 2021 at 5:51
  • kindly share the source dataframe as a dictionary : df.to_dict() Commented Dec 16, 2021 at 6:00
  • Edited my question and put the code with converting data frame to a dictionary. Commented Dec 16, 2021 at 6:11

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the answer. This solved my problem!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.