日期上的 Pandas 数据透视表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9962822/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pandas pivot_table on date
提问by John
I have a pandas DataFramewith a date column. It is not an index.
我有一个DataFrame带有日期列的熊猫。它不是索引。
I want to make a pivot_table on the dataframe using counting aggregate per month for each location.
我想使用每个位置每月的计数聚合在数据帧上创建一个 pivot_table。
The data look like this:
数据如下所示:
['INDEX'] DATE LOCATION COUNT 0 2009-01-02 00:00:00 AAH 1 1 2009-01-03 00:00:00 ABH 1 2 2009-01-03 00:00:00 AAH 1 3 2009-01-03 00:00:00 ABH 1 4 2009-01-04 00:00:00 ACH 1
I used:
我用了:
pivot_table(cdiff, values='COUNT', rows=['DATE','LOCATION'], aggfunc=np.sum)
pivot_table(cdiff, values='COUNT', rows=['DATE','LOCATION'], aggfunc=np.sum)
to pivot the values. I need a way to convert cdiff.DATE to a month rather than a date. I hope to end up with something like: The data look like this:
旋转值。我需要一种将 cdiff.DATE 转换为月份而不是日期的方法。我希望最终得到类似的结果:数据如下所示:
MONTH LOCATION COUNT January AAH 2 January ABH 2 January ACH 1
I tried all manner of strftimemethods on cdiff.DATE with no success. It wants to apply the to strings, not series object.
我strftime在 cdiff.DATE 上尝试了各种方法,但都没有成功。它想将 应用于字符串,而不是系列对象。
回答by Wes McKinney
I would suggest:
我会建议:
months = cdiff.DATE.map(lambda x: x.month)
pivot_table(cdiff, values='COUNT', rows=[months, 'LOCATION'],
aggfunc=np.sum)
To get a month name, pass a different function or use the built-in calendar.month_name. To get the data in the format you want, you should call reset_indexon the result, or you could also do:
要获取月份名称,请传递不同的函数或使用内置的calendar.month_name. 要以您想要的格式获取数据,您应该调用reset_index结果,或者您也可以这样做:
cdiff.groupby([months, 'LOCATION'], as_index=False).sum()
cdiff.groupby([months, 'LOCATION'], as_index=False).sum()

