(矢量化)逐单元遍历两个数据帧,并查找其中一个是否是另一个的一部分



我有一个包含颜色和材料参数的数据帧,另一个包含数据。我想逐个单元格检查数据数据帧是否包含参数数据帧中的任何数据我知道我应该使用矢量化,但我不确定如何

parameter = pd.DataFrame({'color': ['red','blue','green'],
'material': ['wood','metal','plastic']})

data = pd.DataFrame({'name': ['my blue color','red chair','green rod'],
'description': ['it is a great color','made with wood','made with metal']})

我想创建一个包含参数的新列。这是我需要的输出。

data['attribute2']= ['','wood','metal']
print(data)
color             material attribute attribute2
0  my blue color  it is a great color      blue           
1      red chair       made with wood       red       wood
2      green rod      made with metal     green      metal

以下代码过滤colormaterial,它们能够提取颜色和材质。

data['attribute'] = data['name'].apply(lambda name: ','.join([c for c in parameter['color'].tolist() if c in name]))
data['attribute2'] = data['description'].apply(lambda desc: ','.join([m for m in parameter['material'].tolist() if m in desc]))

输出:

属性>这是一种很棒的颜色用木材制成由金属制成
索引颜色材料
0我的蓝色蓝色
1红色椅子红色木材
2绿色棒绿色金属

相关内容

最新更新