组合列值匹配的两个数据框

时间:2021-04-28 19:48:51

标签: python pandas merge

我有两个包含相似列的数据框:

  ID  prop1
1 UUU &&&
2 III ***
3 OOO )))
4 PPP %%%

  ID  prop2
1 UUU 1234 
2 WWW 4567
3 III 7890
5 EEE 0123
6 OOO 3456
7 RRR 6789
8 PPP 9012

我需要合并这两个 ID 匹配的数据帧,并将 prop2 列添加到原始数据中。

  ID  prop1 prop1
1 UUU &&&   1234
2 III ***   7890
3 OOO )))   3456
4 PPP %%%   9012

我尝试了合并、连接、连接、for、iter 等的所有组合。它要么合并失败,要么丢失索引,要么直接删除列值。

2 个答案:

答案 0 :(得分:3)

您可以使用pd.merge()

pd.merge(df1, df2, on='ID')

输出:

    ID prop1  prop2
0  UUU   &&&   1234
1  III   ***   7890
2  OOO   )))   3456
3  PPP   %%%   9012

您也可以使用 df.merge() 如下::

df1.merge(df2, on='ID')

同样的结果。

无论使用 .merge() 还是 pd.merge()df.merge() 上的默认参数都是 how='inner'。因此,您已经在执行内部联接而不指定 how= 参数。

更复杂的场景:

如果需要更复杂的情况来维护df1的索引1, 2, 3, 4而不是0, 1, 2, 3,可以通过在合并前重置索引然后在临时{{重置索引时生成的 {1}} 列:

index

输出:

df1.reset_index().merge(df2, on='ID').set_index('index')

现在,保留原始 ID prop1 prop2 index 1 UUU &&& 1234 2 III *** 7890 3 OOO ))) 3456 4 PPP %%% 9012 的索引 1 2 3 4

或者,如果您不希望轴标签 df1 出现在行索引的顶部,您可以执行 rename_axis() 如下:

index

输出:

df1.reset_index().merge(df2, on='ID').set_index('index').rename_axis(index=None)

答案 1 :(得分:0)

您还可以使用 .map 将 prop2 值添加到原始数据框中,其中 ID 列值匹配。

df1['prop2'] = df1['ID'].map(dict(df2[['ID', 'prop2']].to_numpy())

如果原始数据框中的任何 ID 不在第二个数据框中(因此没有可以传递的 prop2 值,您可以通过添加 .fillna() 与值来填补这些漏洞您的选择。

df1['prop2'] = df1['ID'].map(dict(df2[['ID', 'prop2']].to_numpy()).fillna(your_fill_value_here)