'Extract value from first column in pandas dataframe and add it in file name while saving

I have following dataframe

year   city         population
2002   Chicago      100000
2002   Dallas       150000
2002   Denver       200000

I want to extract "2002" (One file will have same value in each row in first column) from first column and add it in file name I will save

Output file name - 2002_city_population.csv

I am trying this

df = pd.read_csv('city_population.csv', index_col=0)
df.to_csv('2002_city_population.csv')

Currently I am hardcoding "2002" in file name. But I want 2002 to come from first column of file as each file will have different year



Solution 1:[1]

Do you have other years in your dataframe? If so, you could do this:

for year, group in df.groupby("year"):
    group.to_csv(f"{year}_city_population.csv")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ddejohn