只是想序言这个问题是从我之前可以找到的here问题演变而来的。我有一些后续行动最终改变了原来的问题所以我们在这里......
假设我们有以下数据框:
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
但是,我遇到了部分匹配产生的匹配问题。在上面的输出中注意 cheape 将如何匹配“最便宜”而池将匹配“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'}
这就是为什么我要完全匹配以防止出现任何重复/不相关的值。
干杯
答案 0 :(得分:1)
这是一个与我的第一个一致的解决方案。 eval
按空格分割字符串。
str.split(' ')
<强>结果强>
import pandas as pd
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.split(' '))
return ' | '.join(map(labels.get, x))
df['values'] = df['keywords'].map(matcher)
答案 1 :(得分:0)
试试这个:
df['values'] = (df['keywords']
.str.split(expand=True)
.apply(lambda x: x.map(labels).add(' | ').fillna(''))
.sum(axis=1)
.str.rstrip(' | ')
.replace('', 'N/A'))
结果:
In [60]: df
Out[60]:
keywords values
0 cheapest cheap shoes budget
1 luxury shoes expensive
2 cheap hiking shoes budget | sport
3 liverpool N/A