如何验证两个不同的.csv文件列id与python匹配?

时间:2015-02-27 19:22:38

标签: python python-2.7 csv pandas

我有两个不同的.csv文件,但它们具有相同的id列。

file_1.csv:
id, column1, column2
4543DFGD_werwe_23, string
4546476FGH34_wee_24, string
....
45sd234_w32rwe_2342342, string

另一个:

file_1.csv:
id, column3, column4
4543DFGD_werwe_23, bla bla bla
4546476FGH34_wee_24, bla bla bla
....
45sd234_w32rwe_2342342, bla bla bla

如何验证这两列是匹配的(具有相同的id)还是与csv模块或pandas相同?

2 个答案:

答案 0 :(得分:3)

加载后,您可以在ID列上调用equals

df['id'].equals(df1['id'])

这将返回True False In [3]: df = pd.DataFrame({'id':np.arange(10)}) df1 = pd.DataFrame({'id':np.arange(10)}) df.id.equals(df1.id) Out[3]: True In [7]: df = pd.DataFrame({'id':np.arange(10)}) df1 = pd.DataFrame({'id':[0,1,1,3,4,5,6,7,8,9]}) df.id.equals(df1.id) Out[7]: False In [8]: df.id == df1.id Out[8]: 0 True 1 True 2 False 3 True 4 True 5 True 6 True 7 True 8 True 9 True Name: id, dtype: bool 如果它们完全相同,长度相同且值相同

df = pd.read_csv('file_1.csv')
df1 = pd.read_csv('file_2.csv') # I'm assuming your real other csv is not the same name as file_1.csv

加载csvs:

df.id.equals(df1.id)

然后你可以进行与上面相同的比较:

df = pd.read_csv('file_1.csv', usecols=['id'])
df1 = pd.read_csv('file_2.csv', usecols=['id'])

如果您只想比较id列,可以指定加载该列:

{{1}}

答案 1 :(得分:1)

通过csv模块:

  1. 打开文件。
  2. csv reader()方法的读者文件。
  3. 创建字典作为行中的第一项是键,值是行。
  4. 使用set intersection方法从字典中获取相同的密钥。
  5. 打印结果。
  6. 代码:

    import csv
    
    file1 =  '/home/vivek/Desktop/stackoverflow/fil1.csv'
    file2 =  '/home/vivek/Desktop/stackoverflow/fil2.csv'
    
    with open(file1) as fp1:
        root = csv.reader(fp1)
        rows1 = {}
        for i in root:
            rows1[i[0]]=i
        if "id" in rows1:
            del rows1["id"]
    
    with open(file2) as fp1:
        root = csv.reader(fp1)
        rows2 = {}
        for i in root:
            rows2[i[0]]=i
        if "id" in rows2:
            del rows2["id"]
    
    result = set(rows1.keys()).intersection(set(rows2.keys()))
    
    print "Same Id :", list(result)
    

    输出:

    vivek@vivek:~/Desktop/stackoverflow$ python 27.py
    Same Id : ['4546476FGH34_wee_24', '4543DFGD_werwe_23', '45sd234_w32rwe_2342342']