Skip to main content
 首页 » 编程设计

Python,如何合并 2 个 pandas DataFrame

2024年10月25日9mfrbuaa

假设我有两个不同索引的 pandas Dataframe 例如:

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 具有较小的大小

请您参考如下方法:

在这种情况下你可以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