Python DataFrame:将一列转换为多列 [英] Python DataFrame: transpose one column into multiple column

查看:23
本文介绍了Python DataFrame:将一列转换为多列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的数据帧:

df = pd.DataFrame({'month':['2017-09-27','2017-09-27','2017-09-28','2017-09-29'],'Cost':[100,500,200,300]})

如何才能获得这样的df:

2017-09-27   2017-09-28    2017-09-29
  100            200          300
  500            NULL         NULL  

提前谢谢!

推荐答案

使用cumcount计算items within each group的"累计计数"。我们将使用这些值(如下所示)作为索引标签。

In [97]: df['index'] = df.groupby('month').cumcount()

In [98]: df
Out[98]: 
   Cost       month  index
0   100  2017-09-27      0
1   500  2017-09-27      1
2   200  2017-09-28      0
3   300  2017-09-29      0

通过pivoting

即可得到想要的结果
In [99]: df.pivot(index='index', columns='month', values='Cost')
Out[99]: 
month  2017-09-27  2017-09-28  2017-09-29
index                                    
0           100.0       200.0       300.0
1           500.0         NaN         NaN

这篇关于Python DataFrame:将一列转换为多列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆