我有一个包含颜色和材料参数的数据帧,另一个包含数据。我想逐个单元格检查数据数据帧是否包含参数数据帧中的任何数据我知道我应该使用矢量化,但我不确定如何
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
以下代码过滤color
和material
,它们能够提取颜色和材质。
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 | 绿色棒 | 由金属制成绿色 | 金属 |