I have a dataframe with the following information :
Country | Region | Population |
---|---|---|
France | Pas de Calais | 500000 |
France | Provence | 200000 |
Switzerland | Geneva | 400000 |
United States | Florida | 1200000 |
Could you please indicate to me how I can process to get one CSV-file per country, with all data for that country ?
Many thanks in advance for your guideline
CodePudding user response:
df.groupby("Country").apply(lambda df_country: df_country.to_csv(df_country.Country[0] ".csv"))
CodePudding user response:
My recomendation is:
data = {'Country': ['France', 'France', 'Switzerland', 'United States'], 'Region': ['Pas de Calais', 'Provence', 'Geneva', ' Florida'], 'Population': [500000, 200000, 400000, 1200000]}
df = pd.DataFrame.from_dict(data)
grouped_df = df.groupby(by = 'Country')
for _, subdf in grouped_df.__iter__():
# save subdataframe
subdf.to_csv()