Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 :

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')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading