【问题标题】:Compare value in a column in one row of csv file to value in next row using python使用python将csv文件一行中的列中的值与下一行中的值进行比较
【发布时间】:2017-09-14 20:14:26
【问题描述】:

接下来我一直在阅读 csv.reader,但没有看到一种方法来比较列中的值从一行到下一行。例如,如果我的数据在 Maps.csv 文件中如下所示:

County1     C:/maps/map1.pdf 
County1     C:/maps/map2.pdf 
County2     C:/maps/map1.pdf 
County2     C:/maps/map3.pdf 
County3     C:/maps/map3.pdf 
County4     C:/maps/map2.pdf 
County4     C:/maps/map4.pdf

如果二线县等于一线县做某事

下面的代码比较行,我想比较当前行和之前行的县值。

import csv.

f = open("Maps.csv", "r+")
ff = csv.reader(f)

pre_line = ff.next()
while(True):
    try:
        cur_line = ff.next()
        if pre_line == cur_line:
            print "Matches"
        pre_line = cur_line
    except:
        break

我知道我可以获取当前值(见下文),但不知道如何获取之前的值。这可能吗?如果是这样,有人可以告诉我怎么做。在尝试解决编写脚本以从 csv 文件中附加 pdf 文件的问题的第三天,我将把咖啡杯扔到我的显示器上。我将这些分解成更小的部分,并使用更简单的数据作为试点。我的文件要大得多。有人建议我在此论坛发帖时一次只关注一个问题。这是我的最新一期。似乎无论我采取什么策略,我似乎都无法以我想要的方式读取数据。啊啊啊啊啊。

CurColor = row[color]

使用python 2.7

【问题讨论】:

  • 只需将您的 csv 文件读入行列表:rows = list(ff)。现在您将整个 csv 作为 lsts 列表保存在内存中

标签: python-2.7 csv


【解决方案1】:

您已经知道如何查找上一行。为什么不从该行获取您需要的列?

import csv.

f = open("Maps.csv", "r+")
ff = csv.reader(f)

pre_line = ff.next()
while(True):
    try:
        cur_line = ff.next()
        if pre_line[0] == cur_line[0]: # <-- compare first column
            print "Matches"
        pre_line = cur_line
    except:
        break

或更简单地说:

pre_line = ff.next()
for cur_line in ff:
    if pre_line[0] == cur_line[0]: # <-- compare first column
        print "Matches"
    pre_line = cur_line

【讨论】:

    【解决方案2】:
    import csv
    
    f = open("Maps.csv", "r+")
    # Use delimiters to split each line into different elements
    # In my example i used a comma. Your csv may have a different delimiter
    # make sure the delimiter is a single character string though
    # so no multiple spaces between "County1     C:/maps/map1.pdf"
    # it should be something like "County1,C:/maps/map1.pdf"
    ff = csv.reader(f, delimiter=',')
    
    COUNTY_INDEX = 0
    
    # each time ff.next() is called, it makes an array variable ['County1', 'C:/maps/map1.pdf ']
    # since you want to compare the value in the first index, then you need to reference it like so
    # the line below will set pre_line = 'County1'
    pre_line = ff.next()[COUNTY_INDEX]
    while(True):
        try:
            # the current line will be 'County1' or 'County2' etc...Depending on which line is read
            cur_line = ff.next()[COUNTY_INDEX]
            if pre_line == cur_line:
                print "Matches"
            pre_line = cur_line
        except:
            break
    

    【讨论】:

      猜你喜欢
      • 2016-10-14
      • 1970-01-01
      • 1970-01-01
      • 2018-07-02
      • 2021-11-05
      • 2013-03-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多