Home > Enterprise >  Extract value from first column in pandas dataframe and add it in file name while saving
Extract value from first column in pandas dataframe and add it in file name while saving

Time:03-09

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

CodePudding user response:

You can do it with a variable and some f-string formatting.

year = df.at[0, 'year']

df.to_csv(f'{year}_city_population.csv')

CodePudding user response:

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")
  • Related