简体   繁体   English

Pandas:遍历列表以匹配 dataframe 中的值

[英]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.我正在使用 dataframe 的美国所有县的 covid 计数。 I've figured out how to isolate one county and export the result to a csv like this:我已经想出了如何隔离一个县并将结果导出到 csv ,如下所示:

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.并循环遍历它们,为每个创建一个 csv。 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?如何使用已知值列表遍历 dataframe 并从每次迭代中创建新的数据帧? 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:解决方案迭代county列的唯一列表:

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

For each county named by name :对于以name命名的每个县:

  • we are selecting rows from dataframe covid where county is equal to name我们从 dataframe covid中选择行,其中county等于name
  • then such selection is saved to CSV file named: name + .csv .然后将此类选择保存到 CSV 文件,名为: name + .csv

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何遍历 pandas dataframe 中的两列以将值添加到列表中 - How to iterate through two columns in a pandas dataframe to add the values to a list 遍历 dataframe 行以匹配列表中的单词 - Iterate through dataframe rows to match word in list 遍历并覆盖熊猫数据框中的特定值 - Iterate through and overwrite specific values in a pandas dataframe 迭代 Pandas 数据帧列中的列表元素并与不同数据帧中的值匹配 - Iterate over list elements in Pandas dataframe column and match with values in a different dataframe 遍历列表和 append 结果到 pandas dataframe - Iterate through a list and append results to a pandas dataframe 遍历 pandas 数据框中的行并匹配列表字典中的值以创建新列 - Iterate through rows in pandas dataframe and match values in a dictionary of lists to create a new column 遍历 Pandas 数据框中的行并匹配列表中的元组并创建一个新的 df 列 - Iterate through rows in pandas dataframe and match tuples from a list and create a new df column 遍历 pandas 数据框列并使用 if 语句进行 eval 并将列值传递给空列表/字典 - Iterate through a pandas dataframe column and eval with an if statement and pass the column values to an empty list/dictionary Pandas 遍历数据框列并连接包含列表的相应行值 - Pandas-iterate through a dataframe column and concatenate corresponding row values that contain a list 遍历数据框的值 - Iterate through values of dataframe
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM