gpt4 book ai didi

python - Pandas groupby 到 to_csv

转载 作者:太空狗 更新时间:2023-10-29 21:33:23 24 4
gpt4 key购买 nike

想要将 Pandas groupby 数据帧输出到 CSV。尝试了各种 StackOverflow 解决方案,但没有奏效。

Python 3.6.1, Pandas 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’方法”

最佳答案

尝试这样做:

week_grouped = df.groupby('week')
week_grouped.sum().reset_index().to_csv('week_grouped.csv')

这会将整个数据帧写入文件。如果您只需要这两列,

week_grouped = df.groupby('week')
week_grouped.sum().reset_index()[['week', 'count']].to_csv('week_grouped.csv')

这里逐行解释原代码:

# This creates a "groupby" object (not a dataframe object) 
# and you store it in the week_grouped variable.
week_grouped = df.groupby('week')

# This instructs pandas to sum up all the numeric type columns in each
# group. This returns a dataframe where each row is the sum of the
# group's numeric columns. You're not storing this dataframe in your
# example.
week_grouped.sum()

# Here you're calling the to_csv method on a groupby object... but
# that object type doesn't have that method. Dataframes have that method.
# So we should store the previous line's result (a dataframe) into a variable
# and then call its to_csv method.
week_grouped.to_csv('week_grouped.csv')

# Like this:
summed_weeks = week_grouped.sum()
summed_weeks.to_csv('...')

# Or with less typing simply
week_grouped.sum().to_csv('...')

关于python - Pandas groupby 到 to_csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47602097/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com