只想先说明这个问题是从我以前的问题演变而来的,可以在这里找到。我有一些后续行动最终改变了原来的问题,所以我们在这里..
假设我们有以下数据框:
d = {'keywords' :['cheapest cheap shoes', 'luxury shoes', 'cheap hiking shoes','liverpool']}
keywords = pd.DataFrame(d,columns=['keywords'])
In [7]: keywords
Out[7]:
keywords
0 cheapest cheap shoes
1 luxury shoes
2 cheap hiking shoes
3 liverpool
然后创建一个字典,其中包含我想与 DataFrame 中的值匹配的关键字
labels = {'cheape' : 'budget', 'cheap' : 'budget', 'luxury' : 'expensive',
'hiking' : 'sport', 'pool': 'pool'}
提供给我的原始答案帮助解决了字典中匹配键的问题
d = {'keywords' :['cheapest cheap shoes', 'luxury shoes', 'cheap hiking
shoes','liverpool']}
keywords = pd.DataFrame(d,columns=['keywords'])
labels = {'cheape' : 'budget', 'cheap' : 'budget', 'luxury' :
'expensive','hiking' : 'sport', 'pool': 'pool'}
df = pd.DataFrame(d)
def matcher(k):
x = (i for i in labels if i in k)
return ' | '.join(map(labels.get, x))
df['values'] = df['keywords'].map(matcher)
keywords values
0 cheapest cheap shoes budget | budget
1 luxury shoes expensive
2 cheap hiking shoes budget | sport
3 liverpool pool
但是,我遇到了部分匹配导致的匹配问题。在上面的输出中,请注意,cheapest将如何匹配“cheapest”,而pool将如何匹配“liverpool”
所以我的问题是:有没有办法让我的字典与关键字中的值完全匹配,从而跳过部分匹配?
我想要的结果是:
keywords values
0 cheapest cheap shoes budget
1 luxury shoes expensive
2 cheap hiking shoes budget | sport
3 liverpool N/A
旁注 - 字典将扩展以包含绑定到相同值的键。这是为了捕获任何拼写变化或拼写错误,例如{'car' : 'Automobile', 'cars' : 'Automobile', 'carss' : 'Automobile'}
这就是为什么我想精确匹配以防止出现任何重复/不相关的值。
干杯