Reputation: 37
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.
Upvotes: 0
Views: 439
Reputation: 3598
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
:
covid
where county
is equal to name
name
+.csv
.Upvotes: 1