gpt4 book ai didi

python - 如何使用python csv reader查看A列中的行是否存在于B列中

转载 作者:太空宇宙 更新时间:2023-11-03 19:51:12 24 4
gpt4 key购买 nike

我的 csv 文件中有两列

ColumnA ColumnB
jon don
eric cathrine
don sony
jay jon
ron
anne

我想做的是检查columnA中的每个值是否存在于ColumnB中,在这种情况下,columnB中仅存在“jon”和“don”我正在使用 python 及其 csv 阅读器,到目前为止我已经使用了以下代码

with open('samplefile.csv', 'r') as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
for line in csvreader:
if line[0] not in line[1]:
print(line[0]+ " Does not exist")

这不起作用,因为我的代码逐行比较而不是列 A 中的每个值与列 B 中的任何值我还尝试将 csv 中的值放入列表中,但这确实有效,因为它还将 columnB 中的空值附加到第二个列表中。任何帮助表示赞赏。我不限于 csv 阅读器,我可以使用任何其他库,例如 pandas。

最佳答案

像这样更改您的代码:

with open('samplefile.csv', 'r') as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
second_column = [l[1] for l in csvreader]
first_column = [l[0] for l in csvreader]
for line in first_column:
if line not in second_column:
print(f"{line} Does not exist")

关于python - 如何使用python csv reader查看A列中的行是否存在于B列中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59831179/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com