【发布时间】:2018-08-13 18:16:30
【问题描述】:
第一次发帖,如果我的格式关闭,请提前道歉。
这是我的问题:
我创建了一个包含多行文本的 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
非常感谢任何帮助或指导。
干杯
【问题讨论】:
标签: python python-3.x pandas dictionary string-matching