-1

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.

Green Finance
  • 195
  • 12

2 Answers2

0

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

was taking from here: Merge cells with pandas

David Amar
  • 11
  • 2
0

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
mrCopiCat
  • 899
  • 3
  • 15
  • Sorry, I have edited my original post. I do not want it in the form of index. Only a regular column in a dataframe. The solution makes it into index – Green Finance Aug 27 '22 at 19:51
  • 4
    Im afraid that's not possible in pandas dataframes .. , you'll have to use tring manipulation. – mrCopiCat Aug 27 '22 at 19:52