我有一个如下所示的数据框:
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
提前致谢!
Use cumcount https://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.cumcount.html计算“累积计数”每组内的项目 http://pandas.pydata.org/pandas-docs/stable/groupby.html#enumerate-group-items。我们将使用这些值(如下)作为索引标签。
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 https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.pivot.html:
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)