如果我的格式化关闭,第一次发布如此道歉.
这是我的问题:
我创建了一个包含多行文本的Pandas数据框:
d = {'keywords' :['cheap shoes', 'luxury shoes', 'cheap hiking shoes']}
keywords = pd.DataFrame(d,columns=['keywords'])
In [7]: keywords
Out[7]:
keywords
0 cheap shoes
1 luxury shoes
2 cheap hiking shoes
现在我有一个包含以下键/值的字典:
labels = {'cheap' : 'budget', 'luxury' : 'expensive', 'hiking' : 'sport'}
我想要做的是找出数据框中是否存在字典中的键,如果存在,则返回适当的值
我能够使用以下方法实现这一目标:
for k,v in labels.items():
keywords['Labels'] = np.where(keywords['keywords'].str.contains(k),v,'No Match')
但是,输出缺少前两个键,只捕获最后一个“远足”键
keywords Labels
0 cheap shoes No Match
1 luxury shoes No Match
2 cheap hiking shoes sport
另外,我还想知道是否有一种方法可以捕获由|分隔的字典中的多个值,所以理想的输出看起来像这样
keywords Labels
0 cheap shoes budget
1 luxury shoes expensive
2 cheap hiking shoes budget | sport
非常感谢任何帮助或指导.
干杯