【问题标题】:How to merge csv file line by line python如何逐行合并csv文件python
【发布时间】: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

【问题讨论】:

  • 试试concatdf_out = pd.concat([a, b], axis=1)
  • 这能回答你的问题吗? Pandas Merging 101
  • 确实,concat 是要走的路。您使用了merge,它在后台进行了 JOIN,因此产生了不希望的结果。
  • @chrisA concat 对 csv 文件有效吗?
  • 哦,我明白了,我想我必须更改已有的功能。非常感谢@ChrisA

标签: python python-3.x pandas csv merge


【解决方案1】:

使用pandas.concat 组合DataFrame:

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)

【讨论】:

    【解决方案2】:

    您可以使用pandas.join

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

    【讨论】:

      猜你喜欢
      • 2020-07-22
      • 1970-01-01
      • 2013-06-19
      • 2016-04-19
      • 2018-04-26
      • 2013-04-29
      • 1970-01-01
      • 1970-01-01
      • 2020-09-03
      相关资源
      最近更新 更多