使用Python Pandas比较两个CSV文件

9

我有两个csv文件,都包含两列。

第一个文件包含产品ID,第二个文件包含序列号。

我需要查找第一个csv中的所有序列号,并在第二个csv中查找匹配项。结果报告将在单独的一列中显示匹配的序列号以及每个csv中对应的产品ID。

我尝试修改以下代码,但没有成功。

你会如何处理这个问题?

import pandas as pd
    A=set(pd.read_csv("c1.csv", index_col=False, header=None)[0]) #reads the csv, takes only the first column and creates a set out of it.
    B=set(pd.read_csv("c2.csv", index_col=False, header=None)[0]) #same here
    print(A-B) #set A - set B gives back everything thats only in A.
    print(B-A) # same here, other way around.

你能添加一些示例数据和期望的输出吗?因为目前不太清楚需要什么。 - jezrael
3个回答

9

我想你需要使用merge来进行操作:

A = pd.DataFrame({'product id':   [1455,5452,3775],
                    'serial number':[44,55,66]})

print (A)

B = pd.DataFrame({'product id':   [7000,2000,1000],
                    'serial number':[44,55,77]})

print (B)

print (pd.merge(A, B, on='serial number'))
   product id_x  serial number  product id_y
0          1455             44          7000
1          5452             55          2000

只需要进行小的修改,如何在上面的代码片段中以输入的方式给出两个文件名,而不是硬编码数值? - user7609771
如果您有一个xlsx文件,只需使用a = pd.read_csv("path-to-file")a = pd.read_excel("path-to-file")。但是,您需要安装openpyxl才能打开Excel文件。 - Hercislife

4

试试这个:

A = pd.read_csv("c1.csv", header=None, usecols=[0], names=['col']).drop_duplicates()
B = pd.read_csv("c2.csv", header=None, usecols=[0], names=['col']).drop_duplicates()
# A - B
pd.merge(A, B, on='col', how='left', indicator=True).query("_merge == 'left_only'")
# B - A
pd.merge(A, B, on='col', how='right', indicator=True).query("_merge == 'right_only'")

1
你可以将df转换为Sets,这样在比较数据时会忽略索引,然后使用set symmetric_difference
ds1 = set([ tuple(values) for values in df1.values.tolist()])
ds2 = set([ tuple(values) for values in df2.values.tolist()])

ds1.symmetric_difference(ds2)
print df1 ,'\n\n'
print df2,'\n\n'

print pd.DataFrame(list(ds1.difference(ds2))),'\n\n'
print pd.DataFrame(list(ds2.difference(ds1))),'\n\n'

df1

id  Name  score isEnrolled               Comment
0  111  Jack   2.17       True  He was late to class
1  112  Nick   1.11      False             Graduated
2  113   Zoe   4.12       True                   NaN 

df2

    id  Name  score isEnrolled               Comment
0  111  Jack   2.17       True  He was late to class
1  112  Nick   1.21      False             Graduated
2  113   Zoe   4.12      False           On vacation 

输出
     0     1     2      3          4
0  113   Zoe  4.12   True        NaN
1  112  Nick  1.11  False  Graduated 


     0     1     2      3            4
0  113   Zoe  4.12  False  On vacation
1  112  Nick  1.21  False    Graduated 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接