How to reshape dataframe if they have same index?

前端 未结 3 1345
暗喜
暗喜 2020-12-07 03:36

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 re

相关标签:
3条回答
  • 2020-12-07 04:20

    You can use pivot with cumcount :

    a = df.groupby(level=0).cumcount()
    df = pd.pivot(index=df.index, columns=a, values=df[0])
    
    0 讨论(0)
  • 2020-12-07 04:22

    Couple of ways

    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
    

    to remove names

    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
    
    0 讨论(0)
  • 2020-12-07 04:29

    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
    
    0 讨论(0)
提交回复
热议问题