Home > database >  Combine rows with similar value in a column in python dataframe- like excel merge
Combine rows with similar value in a column in python dataframe- like excel merge

Time:08-28

this is my sample dataframe

data={'ColA':["A","A","B","B"],"ColB":["XYZ","PQR","XYZ","PQR"], "ColC":[4, 100, 100, 19], "ColD" : [0,0,0,0]}
df= pd.DataFrame(data)

I want to do an operation similar to excel merge so that the output should look like this. enter image description here

My objective is to only combine Col A without doing any operations on the other columns or the index. I do not want to turn ColA into an index. Is there an option to do this in python. I need the output for visualization and hence the need for this merge.

CodePudding user response:

Try this solution: df = df.set_index('ColA', append=True).swaplevel(0,1)

was taking from here: Merge cells with pandas

CodePudding user response:

You might want to check the .set_index() method, here's an example of what you can do :

import pandas as pd

data={'ColA':["A","A","B","B"],"ColB":["XYZ","PQR","XYZ","PQR"], "ColC":[4, 100, 100, 19], "ColD" : [0,0,0,0]}
df= pd.DataFrame(data)

df.set_index(['ColA', 'ColB'], inplace=True)

print(df)

output:

           ColC  ColD
ColA ColB            
A    XYZ      4     0
     PQR    100     0
B    XYZ    100     0
     PQR     19     0
  • Related