根据 df1 中的列值查找 df2 中的相交值,并在 df1 中创建一个具有检索值的新列(不匹配的列名)

Lookup intersecting values in df2 based on column values in df1 and create a new column with retrieved value in df1 (non matching column names)

Python 的新手,这是我需要帮助的最新挑战

在 df1 中我有以下数据分布:

data = {'Code': ['53.110.30.0140.','53.110.30.0200.','53.110.30.0240. ','53.110.3130.','53.110.3140.'],
       'AA': ['53','53','53','53','53'],
       'BBB': ['110','110','110','110','110'],
       'CC': ['30','30','30','31','31'],
      'DDDD': ['0140','0200','0240','0030','0040']}

df1 = pd.DataFrame(data, columns=['Code','AA','BBB','CC','DDDD'])

在 df2 中我有以下数据分布:

data2 = {'Size': ['0005','0007','0010','0015','0020','0030','0040','0060','0080','0100','0120','0140','0160','0180','0200','0220','0240'],
         '10': [3,5,2,35,47,19,5,14,27,25,46,18,46,38,17,17,23],
         '31': [48,11,26,4,28,25, 19,42,33,41,25,37,35,5,2,27,29],
         '41': [1,32,38,12,15,39,6,46,5,36,35,25,13,12,50,19,19],
         '20': [6,10,7,4,47,25,20,44,20,31,9,44,26,17,20,33,39],
         '21': [21,31,44,12,18,40,8,4,18,32,34,40,29,10,6,14,22],
         '30': [34,50,3,32,8,31,35,40,30,16,37,11,39,16,12,36,22],
         '32': [41,25,32,11,35,18,49,12,31,4,24,8,14,29,28,12,7],
         '40': [48,42,9,11,8,10,39,50,40,46,10,9,42,33,24,7,48],
         '42': [20,21,21,3,23,50,8,41,7,14,14,5,19,9,13,41,48],
         '50': [11,22,24,15,29,46,10,39,46,38,14,13,24,8,14,22,35],
         '51': [41,47,18,26,34,4,19,7,36,13,27,20,21,49,46,30,16],
         '60': [1,1,13,12,1,18,26,7,21,45,5,18,13,4,50,16,15],
         '61': [10,18,24,12,25,48,19,32,5,40,37,8,32,14,15,1,20],
         '62': [34,34,8,21,8,25,7,10,38,16,32,49,21,31,28,13,41]}

df2 = pd.DataFrame(data2, columns=['Size','10','31','41','20','21','30','32','40','42','50','51','60','61','62'])

我想要实现的是在 df1 中添加一个名为 'values' 的列,其值来自 df2,其中满足以下两个匹配条件(换句话说,它们相交的地方,这就是我的值需要)

如前所述,所需结果将返回相交值,例如,如果 df1['DDDD'] = '0140' 和 df1['CC'] = '30',则值从 df2 返回的值应等于“11”。

我尝试过使用合并和映射,但由于我的列名称不匹配而遇到困难

希望我解释清楚了。

提前致谢!

看起来像 lookup 工作:

df2.set_index('Size', inplace=True)
df1['Out'] = df2.lookup(df1['DDDD'], df1['CC'])

输出:

               Code  AA  BBB  CC  DDDD  Out
0   53.110.30.0140.  53  110  30  0140   11
1   53.110.30.0200.  53  110  30  0200   12
2  53.110.30.0240.   53  110  30  0240   22
3      53.110.3130.  53  110  31  0030   25
4      53.110.3140.  53  110  31  0040   19