Combining two csv files using pandas

六月ゝ 毕业季﹏ 提交于 2019-11-28 07:36:45

问题


Can anyone check for me what's wrong with my code. I want it merge two csv file into one csv file.

I hve tried to google and I still cant merge it, it will create new file but will show nothing inside. https://stackoverflow.com/a/16266144/7624469

a.csv

ID    User
A1    Fi
A2    Ki

b.csv

ID    User
A4    Fsdi
A5    Kisd

The output that I want will look like this

combined.csv

ID    User
A1    Fi
A2    Ki
A4    Fsdi
A5    Kisd

test.py

import pandas, sys
import pandas as pd


a = pd.read_csv("C:/JIRA Excel File/a.csv")
b = pd.read_csv("C:/JIRA Excel File/b.csv")

merged = a.merge(b, on='ID')

merged.to_csv('C:/JIRA Excel File/result.csv', index=False)

回答1:


Using df.append:

out = df1.append(df2)
print(out)

   ID  User
0  A1    Fi
1  A2    Ki
0  A4  Fsdi
1  A5  Kisd

with open('C:/JIRA Excel File/result.csv', 'w', encoding='utf-8') as f:
    out.to_csv(f, index=False)



回答2:


It is better to use pd.concat here to combine this frames, not merge:

merged = pd.concat([a,b])

Toy example with your data:

a = pd.DataFrame([['Fi'],['Ki']],columns=['User'], index=['A1','A2'],) #'ID')
b = pd.DataFrame([['Fi'],['Ki']],columns=['User'], index=['A4','A5'],) #'ID')
pd.concat([a,b])

Will output:

    User
A1  Fi
A2  Ki
A4  Fi
A5  Ki


来源:https://stackoverflow.com/questions/46069709/combining-two-csv-files-using-pandas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!