Reputation: 71
I have a data frame with sales related to different countries. I need to crate a different excel for each of the country I have in the dataframe. I am not sure how I can accomplish this in pandas
Upvotes: 0
Views: 333
Reputation: 210832
Alternative version:
for c in df['Country'].unique():
df.loc[df['Country'] == c].to_excel('/path/to/{}.xlsx'.format(c), index=False)
Upvotes: 0
Reputation: 294218
Consider the dataframe 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
We can iterate through a groupby
object and use 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))
This will have created the files
['au.xlsx', 'cn.xlsx', 'jp.xlsx', 'uk.xlsx']
Upvotes: 1