Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reshape dataframe if they have same index?

Tags:

python

pandas

If I have a dataframe like

df= pd.DataFrame(['a','b','c','d'],index=[0,0,1,1])
   0
0  a
0  b
1  c
1  d

How can I reshape the dataframe based on index like below i.e

df= pd.DataFrame([['a','b'],['c','d']],index=[0,1])
  0  1
0  a  b
1  c  d
like image 458
Bharath Avatar asked Dec 06 '25 03:12

Bharath


2 Answers

Let's use set_index, groupby, cumcount, and unstack:

df.set_index(df.groupby(level=0).cumcount(), append=True)[0].unstack()

Output:

   0  1
0  a  b
1  c  d
like image 108
Scott Boston Avatar answered Dec 07 '25 16:12

Scott Boston


You can use pivot with cumcount :

a = df.groupby(level=0).cumcount()
df = pd.pivot(index=df.index, columns=a, values=df[0])
like image 22
jezrael Avatar answered Dec 07 '25 17:12

jezrael