How to change the data form if they have the same index?

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 change the data form based on the index as shown below ie

df= pd.DataFrame([['a','b'],['c','d']],index=[0,1])
  0 1
0 ab
1 cd
+3
source share
3 answers

Use set_index, groupby, cumcountand unstack:

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

Conclusion:

   0  1
0  a  b
1  c  d
+6
source

You can use pivotwith cumcount:

a = df.groupby(level=0).cumcount()
df = pd.pivot(index=df.index, columns=a, values=df[0])
+3
source

1.

In [490]: df.groupby(df.index)[0].agg(lambda x: list(x)).apply(pd.Series)
Out[490]:
   0  1
0  a  b
1  c  d

2.

In [447]: df.groupby(df.index).apply(lambda x: pd.Series(x.values.tolist()).str[0])
Out[447]:
   0  1
0  a  b
1  c  d

3.

In [455]: df.assign(i=df.index, c=df.groupby(level=0).cumcount()).pivot('i', 'c', 0)
Out[455]:
c  0  1
i
0  a  b
1  c  d

In [457]: (df.assign(i=df.index, c=df.groupby(level=0).cumcount()).pivot('i', 'c', 0)
           .rename_axis(None).rename_axis(None, 1))
Out[457]:
   0  1
0  a  b
1  c  d
+2

Source: https://habr.com/ru/post/1686538/


All Articles