【发布时间】:2017-04-14 20:37:29
【问题描述】:
我有一个数据框,其中包含与不同国家/地区相关的销售额。我需要为数据框中的每个国家/地区创建一个不同的 excel。 我不确定如何在 pandas 中完成此操作
【问题讨论】:
标签: pandas
我有一个数据框,其中包含与不同国家/地区相关的销售额。我需要为数据框中的每个国家/地区创建一个不同的 excel。 我不确定如何在 pandas 中完成此操作
【问题讨论】:
标签: pandas
考虑数据框df
df = pd.DataFrame(dict(
Sales=[1, 2, 3, 4],
Country=['jp', 'cn', 'uk', 'au']
))
print(df)
Country Sales
0 jp 1
1 cn 2
2 uk 3
3 au 4
我们可以遍历groupby对象并使用to_excel
for n, g in df.groupby('Country'):
# `n` is the group name, which will be the country
g.to_excel('{}.xlsx'.format(n))
这将创建文件
['au.xlsx', 'cn.xlsx', 'jp.xlsx', 'uk.xlsx']
【讨论】:
替代版本:
for c in df['Country'].unique():
df.loc[df['Country'] == c].to_excel('/path/to/{}.xlsx'.format(c), index=False)
【讨论】: