【问题标题】:How to remove rows from csv based on matching data如何根据匹配数据从 csv 中删除行
【发布时间】:2013-09-27 23:24:06
【问题描述】:

我有大量 csv 格式的数据列表,我需要根据匹配的两个参数从中删除行。

我要删除的数据列表如下所示:

London,James Smith
London,John Oliver
London,John-Smith-Harrison
Paris,Hermione
Paris,Trevor Wilson
New York City,Charlie Chaplin
New York City,Ned Stark
New York City,Thoma' Becket
New York City,Ryan-Dover

然后,主 csv 将根据城市名称与第二列的匹配以及名称与第 9 列中的名称匹配来删除一行。

如果两者都匹配,请删除主 csv 中的行(注意此处未提供此 csv 示例)。

【问题讨论】:

  • 可能有助于更清楚地说明问题。
  • 您好,感谢您的回答,我该怎么做才能使其更清楚。显然,使手头的问题尽可能清晰符合我的利益。亲切的问候 AEA
  • 我只是不确定您是否在为某些事情而苦苦挣扎,或者只是想让某人为您编写代码(我在下面完成了:P)。
  • 你现在测试了吗?
  • 是的,谢谢,工作并接受:)

标签: python python-2.7 csv match


【解决方案1】:

我验证了以下内容可以根据您提供/描述的数据类型进行操作:

import csv
from cStringIO import StringIO

# parse the data you're about to filter with
with open('filters.csv', 'rb') as f:
    filters = {(row[0], row[1]) for row in csv.reader(f, delimiter=',')}

out_f = StringIO()  # use e.g. `with open('out.csv', 'wb') as out_f` for real file output
out = csv.writer(out_f, delimiter=',')

# go thru your rows and see if the pair (row[1], row[8]) is
# found in the previously parsed set of filters; if yes, skip the row
with open('data.csv', 'rb') as f:
    for row in csv.reader(f, delimiter=','):
        if (row[1], row[8]) not in filters:
            out.writerow(row)

# for debugging only
print out_f.getvalue()  # prints the resulting filtered CSV data

注意:{... for ... in ...} 是集合理解语法;根据您的 Python 版本,您可能需要将其更改为等效的 set(... for ... in ...) 才能正常工作。

【讨论】:

  • 确保使用 csv 模块打开文件时使用'rb''wb'。引用docsit must be opened with the ‘b’ flag on platforms where that makes a difference. 对 Python 3 使用 newline=''
【解决方案2】:

如果第 2 列和第 9 列中的元素分别不在列表 L1 和 L2 中,您可以逐行读取数据并将行追加到列表中。

ext = "C:\Users\Me\Desktop\\test.txt"
readL = []

f = open(ext)

for line in f:
    listLine = line.strip().split(',')
    if(listLine[2] in L1 or listLine[9] in L2):
        continue
    readL += [listLine]


f.close()

【讨论】:

  • 我相信他说如果 both 第 2 行和第 9 行在过滤器列表的同一行中找到,则跳过该行;你的代码做了一些不同的事情;在示例 sn-ps 中使用惯用且格式良好的 Python 也是有教育意义的 :) 此外,ext 变量的内容由于反斜杠而格式错误;并且您的代码没有显示如何实际解析 L1L2 的内容; listLine[2] 是第三排,但他说的是第二排;它应该是readL.append(listLine) 等等...看起来你只是在追求廉价的代表。
猜你喜欢
  • 1970-01-01
  • 2022-08-03
  • 1970-01-01
  • 1970-01-01
  • 2020-02-13
  • 2016-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多