【问题标题】:Python: Comparing specific columns in two csv filesPython:比较两个 csv 文件中的特定列
【发布时间】:2011-01-15 15:39:56
【问题描述】:

假设我有两个 CSV 文件(file1 和 file2),内容如下所示:

文件1:

fred,43,Male,"23,45",blue,"1, bedrock avenue"

文件2:

fred,39,Male,"23,45",blue,"1, bedrock avenue"

我想比较这两个 CSV 记录,看看第 0、2、3、4 和 5 列是否相同。我不在乎第 1 列。

最pythonic的方式是什么?

编辑:

一些示例代码将不胜感激。

EDIT2:

请注意嵌入的逗号需要正确处理。

【问题讨论】:

  • 关于 EDIT2:只要使用 import csv 就可以了。
  • @ulidtko 是的,非常感谢。不想成为规定性的,但万一还有我不知道的另一种解决方案。

标签: python csv


【解决方案1】:

我想最好的方法是使用 Python 库:http://docs.python.org/library/csv.html

更新(添加示例)

import csv
reader1 = csv.reader(open('data1.csv', 'rb'), delimiter=',', quotechar='"'))
row1 = reader1.next()
reader2 = csv.reader(open('data2.csv', 'rb'), delimiter=',', quotechar='"'))
row2 = reader2.next()
if (row1[0] == row2[0]) and (row1[2:] == row2[2:]):
    print "eq"
else:
    print "different"

【讨论】:

  • 你能举个例子吗?
  • @Elalfer 我喜欢这个,但它不比较 col 0 吗?
  • @coder999 哦,是的,您要求比较除第一个以外的所有字段。更新示例
  • @Elafer, @coder999: BUG if (row1[0] == row2[0]) and (row[2:] == row[2:]): 应该是 if (row1[0] == row2[0]) and (row1[2:] == row2[2:]):
【解决方案2】:
>>> import csv
>>> csv1 = csv.reader(open("file1.csv", "r"))
>>> csv2 = csv.reader(open("file2.csv", "r"))
>>> while True:
...   try:
...     line1 = csv1.next()
...     line2 = csv2.next()
...     equal = (line1[0]==line2[0] and line1[2]==line2[2] and line1[3]==line2[3] and line1[4]==line2[4] and line1[5]==line2[5])
...     print equal
...   except StopIteration:
...     break
True

更新

3年后,我想我宁愿这样写。

import csv

interesting_cols = [0, 2, 3, 4, 5]

with open("file1.csv", 'r') as file1,\
     open("file2.csv", 'r') as file2:

    reader1, reader2 = csv.reader(file1), csv.reader(file2)

    for line1, line2 in zip(reader1, reader2):
        equal = all(x == y
            for n, (x, y) in enumerate(zip(line1, line2))
            if n in interesting_cols
        )
        print(equal)

【讨论】:

  • 我是新手,它对我真的很有帮助,我实现了我想要的,但不是索引!我们可以使用列名进行压缩吗?如果是,比如何?你能指导一下吗
  • @RaviK 是的,可以使用列名。请参阅Python's built-in csv module 的官方文档和示例。
【解决方案3】:

我会阅读这两条记录,删除第 1 列并比较剩下的内容。 (在python3作品中)

import csv
file1 = csv.reader(open("file1.csv", "r"))
file2 = csv.reader(open("file2.csv", "r"))
r1 = next(file1)
r1.pop(1)
r2 = next(file2)
r2.pop(1)
return r1 == r2

【讨论】:

  • 这不起作用,因为值中嵌入了逗号
  • 您应该提交另一个答案,而不是完全重写这个答案。
【解决方案4】:
# Include required modules

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

# Include required csv files

df_TrainSet = pd.read_csv('../data/ldp_TrainSet.csv')
df_DataSet = pd.read_csv('../data/ldp_DataSet.csv')


# First test
[c for c in df_TrainSet if c not in df_DataSet.columns]

# Second test
[c for c in df_DataSet if c not in df_TrainSet.columns]

在此示例中,我检查两个 CSV 文件是否两个文件中的列相互存在。

【讨论】:

    猜你喜欢
    • 2019-11-24
    • 1970-01-01
    • 1970-01-01
    • 2015-10-30
    • 1970-01-01
    • 2021-04-27
    • 1970-01-01
    • 2014-07-29
    • 2017-05-28
    相关资源
    最近更新 更多