可以说我有两个不同的pandas Dataframe具有不同的索引
例如:

df1:

email                |       other_field
_________________________________________
[email protected]     |           2
[email protected]     |           1
[email protected]     |           6


和df2:

new_field
__________
    1
    7
    4


这两个数据帧具有相同的大小。
如何合并它们两个以得到类似的输出?

df3:

email                |       other_field     |       new_field
________________________________________________________________
[email protected]     |           2           |           1
[email protected]     |           1           |           7
[email protected]     |           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  [email protected]            2          1
1  [email protected]            1          7
2  [email protected]            6          4


如果需要,您可以选择通过ignore_index=True

join也可以:

In [71]:

df1.join(df2)

Out[71]:
              email  other_field  new_field
0  [email protected]            2          1
1  [email protected]            1          7
2  [email protected]            6          4


同样在索引匹配的情况下,直接分配也将起作用:

In [72]:

df1['new_field'] = df2['new_field']
df1
Out[72]:
              email  other_field  new_field
0  [email protected]            2          1
1  [email protected]            1          7
2  [email protected]            6          4

10-06 14:07