Stacking dataframe columns (Pandas)

后端 未结 1 1993
孤街浪徒
孤街浪徒 2020-12-20 00:18

I am looking for a way to pivot a dataframe in reverse direction. To the best of my knowledge, pandas provides a pivot or pivot_table method to transform an EAV df to a \"no

相关标签:
1条回答
  • 2020-12-20 00:50

    Assuming userid is the index, df.stack will do it:

    In [133]: df.stack().reset_index().rename(columns={'userid' : 'E', 'level_1' : 'A', 0 : 'V'})
    Out[133]: 
       E  A  V
    0  0  A  1
    1  0  B  1
    2  0  C  0
    3  1  A  1
    4  1  B  3
    5  1  C  1
    6  2  A  1
    7  2  B  5
    8  2  C  0
    

    If userid is not the index, set it like this:

    df.set_index('userid', inplace=True)
    
    0 讨论(0)
提交回复
热议问题