【问题标题】:Python, how to merge 2 pandas DataFramePython,如何合并2个熊猫数据框
【发布时间】:2014-10-15 15:04:19
【问题描述】:

假设我有两个具有不同索引的不同熊猫数据框 例如:

df1:

email                |       other_field
_________________________________________
email1@email.com     |           2
email2@email.com     |           1
email3@email.com     |           6

和df2:

new_field
__________
    1
    7
    4

这 2 个数据框的大小相同。 我怎样才能合并它们两个以获得类似的输出?

df3:

email                |       other_field     |       new_field
________________________________________________________________
email1@email.com     |           2           |           1
email2@email.com     |           1           |           7
email3@email.com     |           6           |           4

我试过了:

df3 = pd.merge(df1, df2, left_index=True, right_index=True)

尽管 df1 和 df2 的大小相同,但 df3 的大小较小

【问题讨论】:

  • 如果长度相同,你可以连接pd.concat([df1,df2], axis=1, ignore_index=True)

标签: python pandas merge dataframe


【解决方案1】:

在这种情况下,您只需 concat

In [70]:

pd.concat([df1,df2],axis=1)

Out[70]:
              email  other_field  new_field
0  email1@email.com            2          1
1  email2@email.com            1          7
2  email3@email.com            6          4

如果需要,您可以选择传递ignore_index=True

join 也可以:

In [71]:

df1.join(df2)

Out[71]:
              email  other_field  new_field
0  email1@email.com            2          1
1  email2@email.com            1          7
2  email3@email.com            6          4

同样在索引匹配的情况下,直接赋值也可以:

In [72]:

df1['new_field'] = df2['new_field']
df1
Out[72]:
              email  other_field  new_field
0  email1@email.com            2          1
1  email2@email.com            1          7
2  email3@email.com            6          4

【讨论】:

    猜你喜欢
    • 2018-11-04
    • 2017-11-03
    • 2020-08-16
    • 2021-05-30
    • 2021-05-31
    • 2016-08-07
    • 2017-06-11
    • 2016-01-01
    相关资源
    最近更新 更多