简体   繁体   English

如何逐行合并csv文件python

[英]How to merge csv file line by line python

Hello I am new to Python and I am trying to merge these two files fileA and fileB into one using this piece of code您好,我是 Python 新手,我正在尝试使用这段代码将这两个文件 fileA 和 fileB 合并为一个

    a = pandas.read_csv(fileA)
    b = pandas.read_csv(fileB)
    b = b.dropna(axis=1)
    merged = b.merge(a, on="day")
    merged.to_csv(output, index=False)

But the problem is instead of it merging line by line it merges the first line of fileA with all lines of fileB!但问题是它不是逐行合并,而是将 fileA 的第一行与 fileB 的所有行合并! below you'll find an example下面你会找到一个例子

content of fileA文件A的内容

numb,day

one,sat
two,sun  
three,mon

content of fileB文件B的内容

day,month,color,shape

sat,apr,black,circle
sun,may,white,triangle
mon,jun,red,square

expected output预期产出

numb,day,month,color,shape

one,sat,apr,black,circle
two,sun,may,white,triangle
three,mon,jun,red,square

what I am actually getting我实际上得到了什么

numb,day,month,color,shape

one,sat,apr,black,circle
one,sat,may,white,triangle
one,sat,mon,jun,red,square
two,sun,apr,black,circle
two,sun,may,white,triangle
two,sun,jun,red,square
.
.
.

So how can I merge the files line by line instead of all of this, or what exactly am I doing wrong here?那么如何逐行合并文件而不是所有这些,或者我在这里做错了什么?

I am using Python 3.7我正在使用 Python 3.7

Use pandas.concat to combine DataFrames:使用pandas.concat组合数据帧:

a = pandas.read_csv(fileA)
b = pandas.read_csv(fileB)
b = b.dropna(axis=1)

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

merged.to_csv('output.csv', index=False)

You can use pandas.join您可以使用pandas.join

a = pandas.read_csv(fileA)
b = pandas.read_csv(fileB)
fileA.join(fileB.set_index('day'), on='day')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM