【发布时间】:2020-06-22 11:19:00
【问题描述】:
您好,我是 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
【问题讨论】:
-
试试
concat:df_out = pd.concat([a, b], axis=1) -
这能回答你的问题吗? Pandas Merging 101
-
确实,
concat是要走的路。您使用了merge,它在后台进行了 JOIN,因此产生了不希望的结果。 -
@chrisA concat 对 csv 文件有效吗?
-
哦,我明白了,我想我必须更改已有的功能。非常感谢@ChrisA
标签: python python-3.x pandas csv merge