Pandas Dataframes

Let’s now save multiple unique, filtered dataframes

Code:

import pandas as pd

import numpy as np

df = pd.read_excel('europe_cities_by_sunshine.xlsx')

for country in df['Country'].unique().tolist():

sub_df = df[df['Country'].isin([country])]

sub_df.to_csv(f'{country}_Rankings_By_Sun.csv', index=False)

Explanation:

Now, we’re going to go through every unique country in the Europe Excel file in the first line of the for loop. The for loop first gets the Country column, then gets all unique countries, then converts these distinct countries into a list so we can cycle through them in a loop. Then, we’re going to create a new, filtered dataframe for only the current country in the for loop (so one for France, Spain, Greece, etc). Then, it will save this sub_df, filtered dataframe, to a csv file and name it dynamically by passing in the country name to the to_csv() function to make it easy to determine which csv file contains which countries.