How do I merge two CSV files based on field and keep same number of attributes on each record?

前端 未结 3 1248
感情败类
感情败类 2021-02-06 11:00

I am attempting to merge two CSV files based on a specific field in each file.

file1.csv

id,attr1,attr2,attr3
1,True,7,\"Purple\"
2,Fal         


        
3条回答
  •  离开以前
    2021-02-06 11:30

    You can use pandas to do this:

    import pandas
    
    csv1 = pandas.read_csv('filea1.csv')
    csv2 = pandas.read_csv('file2.csv')
    merged = csv1.merge(csv2, on='id')
    merged.to_csv("output.csv", index=False)
    

    I haven't tested this yet but it should put you on the right track until I can try it out. The code is quite self-explanatory; first you import the pandas library so that you can use it. Then using pandas.read_csv you read the 2 csv files and use the merge method to merge them. The on parameter specifies which column should be used as the "key". Finally, the merged csv is written to output.csv.

提交回复
热议问题