如何将一列中的值映射到另一个数据框的其他两列,并提取两列中的匹配值?

时间:2020-11-09 14:53:29

标签: python pandas

我有两个数据框

df1

NAME
AB2
AB3
AB45
AB5
AB6
AB776
AB845
AB9
AB10

df2

G1  G2  Value
AB2 AB3   5
AB3 AB2   5
AB2 AB2   4
CXY AB3   0
AB3 GTZ   8
AB5 AB6   4
AB9 NUT3    6
CVC FGT   5
MKH CTY   8
LMN VUT   9
AB776   AB776   1
AB845   AB776   8

我想将df1['NAME']的值映射到df2['G1']df2['G2']并提取与值匹配的列。

我尝试如下:

df = df2[df2['G1'].isin(df1['NAME']) | df2['G2'].isin(df1['NAME'])]

但是它也提取与单个列匹配的所有值。如果它同时映射到两个列,我想返回

预期输出为:

G1    G2    Value
AB2   AB3   5
AB3   AB2   5
AB2   AB2   4
AB5   AB6   4
AB776   AB776   1
AB845   AB776   8

2 个答案:

答案 0 :(得分:1)

您要查找&而不是|的条件吗?

df2[df2['G1'].isin(df1['NAME']) & df2['G2'].isin(df1['NAME'])]

输出:

       G1     G2  Value
0     AB2    AB3      5
1     AB3    AB2      5
2     AB2    AB2      4
5     AB5    AB6      4
10  AB776  AB776      1
11  AB845  AB776      8

答案 1 :(得分:1)

我认为您需要&

In [1242]: df2[df2['G1'].isin(df1['NAME']) & df2['G2'].isin(df1['NAME'])]
Out[1242]: 
       G1     G2  Value
0     AB2    AB3      5
1     AB3    AB2      5
2     AB2    AB2      4
5     AB5    AB6      4
10  AB776  AB776      1
11  AB845  AB776      8