如何在多个excel文件中拆分熊猫数据框
答
考虑数据框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)
欢迎来到Stackoverflow!很显然,您需要熟悉我们如何提问。这个网站是一个很好的资源,如果你遵循一些简单的指导方针,你将能够更有效地利用它。请阅读[*** MCVE ***](http://stackoverflow.com/help/mcve)和[*** HowToAsk ***](http://stackoverflow.com/help/how-to-ask )更好地了解我们的期望。这是为了帮助你解答你的问题。希望有所帮助。 – piRSquared