[英]How to merge csv file line by line python
您好,我是 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)
但问题是它不是逐行合并,而是将 fileA 的第一行与 fileB 的所有行合并! 下面你会找到一个例子
文件A的内容
numb,day
one,sat
two,sun
three,mon
文件B的内容
day,month,color,shape
sat,apr,black,circle
sun,may,white,triangle
mon,jun,red,square
预期产出
numb,day,month,color,shape
one,sat,apr,black,circle
two,sun,may,white,triangle
three,mon,jun,red,square
我实际上得到了什么
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
.
.
.
那么如何逐行合并文件而不是所有这些,或者我在这里做错了什么?
我正在使用 Python 3.7
使用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)
您可以使用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.