Python熊猫:合并部分重叠的数据框

时间:2019-06-26 05:43:16

标签: python pandas

我有一个数据框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
  • namedf1之间没有通用的df2值。
  • df2.group还包含值G1G2
  • df2的列可以是df1的一部分(例如col2col4col5),也可以是{{1} }(例如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中没有col7,因此在合并的数据框中,所有源自df1的行在df1下的值为0。对于源自col7的所有行以及df2唯一的列col1col3的所有列相同。

1 个答案:

答案 0 :(得分:0)

原来比我想象的要容易得多

df_union_all= pd.concat([df1, df2])
相关问题