小编J_W*_*Win的帖子

在 Pandas Dataframe 中查找多个字典键并返回多个匹配值

第一次发帖,如果我的格式不正确,请提前道歉。

这是我的问题:

我创建了一个包含多行文本的 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 …
Run Code Online (Sandbox Code Playgroud)

python dictionary string-matching python-3.x pandas

4
推荐指数
1
解决办法
2070
查看次数

标签 统计

dictionary ×1

pandas ×1

python ×1

python-3.x ×1

string-matching ×1