【问题标题】:Python pandas: merging partially overlapping dataframesPython pandas:合并部分重叠的数据框
【发布时间】:2019-06-26 05:43:16
【问题描述】:

我有一个数据框,df1,例如:

name | group | col1 | col2 | col3 | col4 | col5
id1  | G1    |
id2  | G1    |
id3  | G1    |
id4  | G2    |
id5  | G2    |
id6  | G2    |
...
id10
  • col1col2等的值为浮点数,>= 0。
  • name 的值是字符串,其中每个名称唯一标识每一行
  • group 的值是字符串。此列描述了一组名称,并包含在内以保持完整性。

还有另一个数据框,df2,比如:

name | group | col2 | col4 | col5 | col7 |
id11 | G1    |
id12 | G1    |
id13 | G1    |
id14 | G2    |
id15 | G2    |
id16 | G2    |
...
id20
  • df1df2 之间没有共同的name 值。
  • df2.group 还包含值 G1G2
  • df2 的列可以是df1 的一部分(例如col2col4col5),也可以是df2 独有的(例如col7)。

我希望像这样合并这两个数据框:

name | group | col1 | col2 | col3 | col4 | col5 | col7
id1  | G1    |                                  |  0
id2  | G1    |                                  |  0
id3  | G1    |                                  |  0
id4  | G2    |                                  |  0
...
id10 | G2    |  0   |      |  0   |      |      |
id11 | G1    |  0   |      |  0   |      |      |
id12 | G1    |  0   |      |  0   |      |      |
...
id20
  • df2的行追加到df1,得到它们列的集合。
  • 如果原始数据框中的一行在新列下没有值,则合并数据框中的值为零。例如df1 中没有 col7,因此在合并的数据帧中,源自 df1 的所有行将在 col7 下获得值 0。对于源自df2 的所有行以及col1col3 列都是相同的,它们是df1 独有的。

【问题讨论】:

  • 那么你的问题是什么?

标签: python pandas


【解决方案1】:

结果比我想象的要容易得多:

df_union_all= pd.concat([df1, df2])

【讨论】:

    猜你喜欢
    • 2021-06-25
    • 1970-01-01
    • 2018-11-03
    • 2018-11-01
    • 1970-01-01
    • 2017-05-10
    • 2021-05-19
    • 2020-04-10
    • 1970-01-01
    相关资源
    最近更新 更多