【发布时间】:2018-05-16 01:45:03
【问题描述】:
想要将 Pandas groupby 数据框输出到 CSV。尝试了各种 StackOverflow 解决方案,但没有奏效。
Python 3.6.1,熊猫 0.20.1
groupby 结果如下:
id month year count
week
0 9066 82 32142 895
1 7679 84 30112 749
2 8368 126 42187 872
3 11038 102 34165 976
4 8815 117 34122 767
5 10979 163 50225 1252
6 8726 142 38159 996
7 5568 63 26143 582
想要一个看起来像这样的 csv
week count
0 895
1 749
2 872
3 976
4 767
5 1252
6 996
7 582
当前代码:
week_grouped = df.groupby('week')
week_grouped.sum() #At this point you have the groupby result
week_grouped.to_csv('week_grouped.csv') #Can't do this - .to_csv is not a df function.
阅读 SO 解决方案:
output groupby to csv file pandas
week_grouped.drop_duplicates().to_csv('week_grouped.csv')
结果: AttributeError:无法访问“DataFrameGroupBy”对象的可调用属性“drop_duplicates”,请尝试使用“apply”方法
Python pandas - writing groupby output to file
week_grouped.reset_index().to_csv('week_grouped.csv')
结果: AttributeError: "无法访问 'DataFrameGroupBy' 对象的可调用属性 'reset_index',请尝试使用 'apply' 方法"
【问题讨论】:
-
如果您来到这里想知道如何将每个单独的 groupby 保存到自己的 CSV 文件中,请参阅this answer。
标签: python pandas csv pandas-groupby