J_W*_*Win 4 python dictionary string-matching python-3.x pandas
第一次发帖,如果我的格式不正确,请提前道歉。
这是我的问题:
我创建了一个包含多行文本的 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
Run Code Online (Sandbox Code Playgroud)
现在我有一个包含以下键/值的字典:
labels = {'cheap' : 'budget', 'luxury' : 'expensive', 'hiking' : 'sport'}
Run Code Online (Sandbox Code Playgroud)
我想做的是找出数据框中是否存在字典中的键,如果存在,则返回适当的值
我能够使用以下方法到达那里:
for k,v in labels.items():
keywords['Labels'] = np.where(keywords['keywords'].str.contains(k),v,'No Match')
Run Code Online (Sandbox Code Playgroud)
但是,输出缺少前两个键并且只捕获最后一个“远足”键
keywords Labels
0 cheap shoes No Match
1 luxury shoes No Match
2 cheap hiking shoes sport
Run Code Online (Sandbox Code Playgroud)
此外,我还想知道是否有办法在以 | 分隔的字典中捕获多个值。,所以理想的输出看起来像这样
keywords Labels
0 cheap shoes budget
1 luxury shoes expensive
2 cheap hiking shoes budget | sport
Run Code Online (Sandbox Code Playgroud)
非常感谢任何帮助或指导。
干杯
这当然是可能的。这是一种方法。
d = {'keywords': ['cheap shoes', 'luxury shoes', 'cheap hiking shoes', 'nothing']}
keywords = pd.DataFrame(d,columns=['keywords'])
labels = {'cheap': 'budget', 'luxury': 'expensive', 'hiking': 'sport'}
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 cheap shoes budget
# 1 luxury shoes expensive
# 2 cheap hiking shoes budget | sport
# 3 nothing
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2070 次 |
| 最近记录: |