匹配熊猫数据框和列表

问题描述

我有一个数据框 df 如下

 Number   PT
     
    5        AA
    
    64       BB
  
    7        CC

然后是另一个对象列表,

myList = [{'label': 'AA','value': 'AA','group': 'A'},{'label': 'BB','value': 'BB','group': 'B'}]

我希望每个 PT 从列表中都有关联的组(如果可用),所以结果应该是这样的

    Number       PT    group
         
        5        AA    A
        
        64        BB    B
      
        7        CC    NOT_MATCHED
        

解决方法

d = {'Number': [5,64,7],'PT': ["AA","BB","CC"]}
df = pd.DataFrame(data=d)

myList = [{'label': 'AA','value': 'AA','group': 'A'},{'label': 'BB','value': 'BB','group': 'B'}]    

for i,row in df.iterrows():
  for item in myList:
    if item['value'] == df['PT'][i]:
      df.at[i,'Group'] = item['group']
      break
    else:
      df.at[i,'Group'] = "NOT_MATCHED"
,

尝试:

df['group'] = df.PT.map({tuple(i.values())[0]: tuple(i.values())[
                        2] for i in myList}).fillna('Not Matched')