reshaping a data frame in pandas

安稳与你 提交于 2021-02-08 08:16:19

问题


Is there a simple way in pandas to reshape the following data frame:

df = pd.DataFrame({'n':[1,1,2,2,1,1,2,2],
                   'l':['a','b','a','b','a','b','a','b'],
                   'v':[12,43,55,19,23,52,61,39],
                   'g':[0,0,0,0,1,1,1,1]
                  })

to this format?:

   g  a1 b1 a2 b2
   0  12 43 55 19
   1  23 52 61 39

回答1:


In [75]: df['ln'] = df['l'] + df['n'].astype(str)

In [76]: df.set_index(['g', 'ln'])['v'].unstack('ln')
Out[76]: 
ln  a1  a2  b1  b2
g                 
0   12  55  43  19
1   23  61  52  39

[2 rows x 4 columns]

If you need that ordering then:

In [77]: df.set_index(['g', 'ln'])['v'].unstack('ln')[['a1', 'b1', 'a2', 'b2']]
Out[77]: 
ln  a1  b1  a2  b2
g                 
0   12  43  55  19
1   23  52  61  39

[2 rows x 4 columns]


来源:https://stackoverflow.com/questions/21615158/reshaping-a-data-frame-in-pandas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!