Python 使用 Pandas 合并两个 csv 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46069709/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:27:24  来源:igfitidea点击:

Combining two csv files using pandas

pythonpandascsvdataframeconcat

提问by Fiqri Mfbw

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

任何人都可以检查我的代码有什么问题。我希望它将两个 csv 文件合并为一个 csv 文件。

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

我试过谷歌,但我仍然无法合并它,它会创建新文件但里面什么也不显示。https://stackoverflow.com/a/16266144/7624469

a.csv

一个.csv

ID    User
A1    Fi
A2    Ki

b.csv

b.csv

ID    User
A4    Fsdi
A5    Kisd

The output that I want will look like this

combined.csv

我想要的输出看起来像这样

合并.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)

回答by cs95

Using df.append:

使用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)

回答by Grigory

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

最好在pd.concat这里使用来组合这些帧,而不是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