【发布时间】:2020-08-05 07:28:00
【问题描述】:
到目前为止我的代码:
import csv
myIds = ['1234','3456','76']
countries = []
# open the file
with open('my.csv', 'r') as infile:
# read the file as a dictionary for each row ({header : value})
reader = csv.DictReader(infile)
data = {}
for row in reader:
for header, value in row.items():
try:
data[header].append(value)
except KeyError:
data[header] = [value]
# extract the variables and assign to lists
myFileIds = data['id']
myFileCountry = data['country']
listfromfile = [a + " " + b for a, b in zip(myFileIds, myFileCountry)]
上面在 listfromfile 中给出了如下结果:
listfromfile = ['1 Uruguay', '2 Vatican', '1234 US', '3456 UK', '5678 Brazil','10111 Argentina','234567 Spain']
我的目标是列出在 my.csv 文件中出现 ID 的国家/地区,但 myIds 列表中的 id 也可能不会出现在 my.csv 文件中。然后我需要列表中的那个位置显示为“不受支持的国家/地区”。两个列表的 myIds 和国家应该具有相同的长度,所以我会知道我列表中的第一个 id 对应于另一个列表中的第一个国家等。期望的结果:
myIds = ['1234','3456','76']
countries = ['US', 'UK', 'Unsupported Country']
或者我正在尝试使用熊猫,但也没有运气:(
import pandas as pd
df=pd.read_csv('my.csv')
myIds = ['1234','3456','76']
countries = df.loc[df["id"].isin(myIds),"country"].tolist()
我的.csv:
id country
1 Uruguay
2 Vatican
1234 US
3456 UK
5678 Brazil
10111 Argentina
234567 Spain
有人可以帮我解决这个问题吗?提前致谢!
【问题讨论】:
-
假设文件中的文本与示例中的文本完全相同,要从文件中获取数据框:
pd.read_csv("my.csv", sep=r'\s+')您需要指定分隔符。检查我的答案是否有其他选择。
标签: python python-3.x pandas list csv