Merging two CSV files by a common column python

后端 未结 2 1355
春和景丽
春和景丽 2021-01-21 17:08

I am trying to merge two csv files with a common id column and write the merge to a new file. I have tried the following but it is giving me an error -

import c         


        
2条回答
  •  死守一世寂寞
    2021-01-21 17:16

    Here is an example using pandas

    import sys
    from StringIO import StringIO
    import pandas as pd
    
    TESTDATA=StringIO("""DOB;First;Last
        2016-07-26;John;smith
        2016-07-27;Mathew;George
        2016-07-28;Aryan;Singh
        2016-07-29;Ella;Gayau
        """)
    
    list1 = pd.read_csv(TESTDATA, sep=";")
    
    TESTDATA=StringIO("""Date of Birth;Patient First Name;Patient Last Name
        2016-07-26;John;smith
        2016-07-27;Mathew;XXX
        2016-07-28;Aryan;Singh
        2016-07-20;Ella;Gayau
        """)
    
    
    list2 = pd.read_csv(TESTDATA, sep=";")
    
    print list2
    print list1
    
    common = pd.merge(list1, list2, how='left', left_on=['Last', 'First', 'DOB'], right_on=['Patient Last Name', 'Patient First Name', 'Date of Birth']).dropna()
    print common
    

提交回复
热议问题