gpt4 book ai didi

Python,如何合并 2 个 pandas DataFrame

转载 作者:太空宇宙 更新时间:2023-11-04 03:41:10 24 4
gpt4 key购买 nike

假设我有两个不同索引的 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

关于Python,如何合并 2 个 pandas DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26385843/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com