Guillermina
Guillermina

Reputation: 3657

Iterate over rows and save as csv

I am working with this DataFrame index and it looks like this:

        year    personal    economic    human   rank
country                 
Albania 2008    7.78    7.22    7.50    49
Albania 2009    7.86    7.31    7.59    46
Albania 2010    7.76    7.35    7.55    49
Germany 2011    7.76    7.24    7.50    53
Germany 2012    7.67    7.20    7.44    54

It has 162 countries for 9 years. What I would like to do is:

  1. Create a for loop that returns a new dataframe with the data for each country that only shows the values for personal, economic, human, and rank only.

  2. Save each dataframe as a .csvwith the name of the country the data belong to.

Upvotes: 1

Views: 64

Answers (1)

Vishnudev Krishnadas
Vishnudev Krishnadas

Reputation: 10960

Iterate through unique values of country and year. Get data related to that country and year in another dataframe. Save it.

df.reset_index(inplace=True) # To covert multi-index as in example to columns
unique_val = df[['country', 'year']].drop_duplicates()
for _, country, year in unique_val.itertuples():
    file_name = country + '_' + str(year) + '.csv'
    out_df = df[(df.country == country) & (df.year == year)]
    out_df = out_df.loc[:, ~out_df.columns.isin(['country', 'year'])]
    print(out_df)
    out_df.to_csv(file_name)

Upvotes: 1

Related Questions