将整个列表与另一个数据框中的值匹配

问题描述

我有一个数据框,该数据框的一列中有一个列表,并且想要将该列表中的所有项目与第二个数据框进行匹配。然后应将匹配的值(作为列表)添加到第一个数据框中的新列。

data = {'froots':  [['apple','banana'],['apple','strawberry']]
        }
df1 = pd.DataFrame(data)

data = {'froot':  ['apple','banana','strawberry'],'age': [2,3,5]
        }
df2 = pd.DataFrame(data)

DF1

index fruits
1     ['apple','banana']
2     ['apple','strawberry']

DF2

index fruit age
1     apple 2
2     banana 3
3     strawberry 5

新DF1

index froots                  age
1     ['apple','banana']      [2,3]
2     ['apple','strawberry']  [2,5]

我有一个简单的解决方案,它花了太长时间:

age = list()
for index,row in df1.iterrows():
    numbers = row.froots
    tmp = df2[['froot','age']].apply(lambda x: x['age'] if x['froot'] in numbers else None,axis=1).dropna().tolist()
    age.append(tmp)
df1['age'] = age

也许可以更快地解决这个问题? 预先感谢!

解决方法

df2创建的字典中使用lsit理解,并添加新值到列表中,如果if测试的字典中存在该值:

d = df2.set_index('froot')['age'].to_dict()

df1['ag1e'] = df1['froots'].apply(lambda x: [d[y] for y in x if y in d])
print (df1)
                froots    ag1e
0      [apple,banana]  [2,3]
1  [apple,strawberry]  [2,5]

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...