简体   繁体   中英

Pandas: iterate through a list to match values in a dataframe

I'm working with a dataframe of covid counts for all counties in the US. I've figured out how to isolate one county and export the result to a csv like this:

import pandas as pd
covid = pd.read_csv('https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-counties.csv')
agh = covid[covid['county'] == 'Allegheny']
agh.to_csv('AlleghenyCovid.csv')

Now I want to create a list of counties like this:

countyList = covid.county.unique()

and loop through them to create a csv for each. That's where I'm stuck. How can I use a list of known values to iterate through the dataframe and create new dataframes from each iteration? I've been thinking something like:

for i in countyList:
    if covid['county'] == i:
        ...

but that gives an ambiguous value error. I'm not sure exactly what needs to be defined.

Solution iterate unique list of county column:

for name in covid.county.unique()
    covid.loc[covid.county == name,:].to_csv(name+'.csv')

For each county named by name :

  • we are selecting rows from dataframe covid where county is equal to name
  • then such selection is saved to CSV file named: name + .csv .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM