【问题标题】:How can I match a list value to a single cvs file's row?如何将列表值与单个 csv 文件行匹配?
【发布时间】:2020-11-23 17:51:41
【问题描述】:

我需要将整数值列表与 CVS 文件中的单行进行比较,以找到与该值匹配的行。

'''

firstScore = 90  
secondScore = 80  
thirdScore = 75  

list = [firstScore, secondScore, thirdScore]

'''

csv 数据为:

    Name,first,second,third
    Paul,40,60,30
    Kevin,90,80,75
    Jenny,80,75,90

实际输出应该是与 3 个值匹配的名称:Kevin

【问题讨论】:

  • edit您的问题并添加您正在使用的代码。
  • csv 数据中的括号是怎么回事?

标签: python list csv match reader


【解决方案1】:

由于缺少您的代码,我假设您使用带有 read_csv 的 pandas 包来创建包含上面给出的数据的数据帧 (df)。如果是这样,您可以使用以下方法从您的 df 中检索数据:

 df.loc[(df['first'] == list[0]) & (df['second'] == list[1]) & (df['third'] == list[2])].iloc[:,0]

【讨论】:

    【解决方案2】:

    我不清楚你的数据来自哪里,但这段代码应该涵盖关键逻辑:

    import io
    
    data = '''
    [Name, first, second, third]
    [Paul, 40, 60, 30]
    [Kevin, 90, 80, 75]
    [Jenny, 80, 75, 90]
    '''
    
    lstFind = [str(x) for x in [90, 80, 75]] # convert to string fields
    
    lstAll = []
    
    f = io.StringIO(data)  # load string data as file text
    for row in f: 
      if not row.strip(): continue # skip empty rows
      rowlst = row.strip().replace(" ","")[1:-1].split(",") # convert row to list
      lstAll.append(rowlst) # add to main list
    
    for lst in lstAll:  # each list 
       if lst[1:] == lstFind:
          print(lst[0])    # Kevin
    
      
    

    【讨论】:

    • 输出错误:AttributeError: 'list' object has no attribute 'strip'
    • 您的源数据是列表列表?
    • 不,只是一个整数列表。
    【解决方案3】:

    感谢 Handler (https://stackoverflow.com/users/9659528/handler ) 在此问题结束时解决了该问题。 ''' 导入csv

    list = [firstScore, secondScore, thirdScore]
    
    with open('test.csv', 'rt') as f:
    reader = csv.reader(f, delimiter=',')
    
    # skip the header of your csv
    next(reader)
    
    for row in reader:
      if((list[0] == int(row[1])) and (list[1] == int(row[2])) and (list[2] == int(row[3]))):
        # print name (present in first column -> index 0 of the row) 
        print(row[0])
        break
      else:
        print("No match found..")
    

    '''

    【讨论】:

      猜你喜欢
      • 2020-11-24
      • 2020-08-09
      • 2019-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多