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

标签 python python-3.x pandas csv

我的 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/

相关文章:

python - 为什么函数参数之外的 "self"会出现 "not defined"错误?

python - 如何将python应用程序连接到在线数据库

python - Sphinx 快速入门有限的选项

python - 在不存在预先指定的条件的情况下插入 Pandas 数据框

python - 删除 python 列表中的项目

python - 将字符串转换为路径对象

python - 如何执行从特定代码行开始的 python 文件?

python - Python按顺序运行函数;如果失败,请停止

python - 如何将第一列的值添加到新数组?

python - 线型图看不到 x 轴标签