【问题标题】:How to see if a row in column A exists in Column B with python csv reader如何使用python csv阅读器查看A列中的一行是否存在于B列中
【发布时间】:2020-05-06 22:17:01
【问题描述】:

我在一个 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")

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

【问题讨论】:

    标签: python python-3.x pandas csv


    【解决方案1】:

    像这样更改您的代码:

    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")
    

    【讨论】:

      【解决方案2】:

      对于 pandas,我们可以使用 .isin 返回一个布尔系列:

      df['check'] = df['ColumnA'].isin(df['ColumnB'])
      
      print(df)
        ColumnA   ColumnB  check
      0     jon       don   True
      1    eric  cathrine  False
      2     don      sony   True
      3     jay       jon  False
      4     ron      None  False
      5    anne      None  False
      

      【讨论】:

        【解决方案3】:

        你可以用熊猫来做:

        #df from csv
        df=pd.read_csv('samplefile.csv', header=0)
        #iterate the df
        for index, row in df.iterrows():
            if not row['ColumnA'].isin(df['ColumnB']) :
                print (f"{row['ColumnA']} doesn't exist") 
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-02-07
          • 2021-10-26
          • 2018-04-21
          • 1970-01-01
          • 2022-01-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多