Python DataFrame: transpose one column into multiple column(Python DataFrame:将一列转换为多列)
本文介绍了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:将一列转换为多列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:Python DataFrame:将一列转换为多列


基础教程推荐
猜你喜欢
- 如何在Python中绘制多元函数? 2022-01-01
- 合并具有多索引的两个数据帧 2022-01-01
- 哪些 Python 包提供独立的事件系统? 2022-01-01
- 症状类型错误:无法确定关系的真值 2022-01-01
- 将 YAML 文件转换为 python dict 2022-01-01
- 使用Python匹配Stata加权xtil命令的确定方法? 2022-01-01
- Python 的 List 是如何实现的? 2022-01-01
- 如何在 Python 中检测文件是否为二进制(非文本)文 2022-01-01
- 使用 Google App Engine (Python) 将文件上传到 Google Cloud Storage 2022-01-01
- 使 Python 脚本在 Windows 上运行而不指定“.py";延期 2022-01-01