gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 02:01:29 24 4
gpt4 key购买 nike

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

这是我的问题:

我创建了一个包含多行文本的 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

非常感谢任何帮助或指导。

干杯

最佳答案

这当然是可能的。这是一种方法。

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

关于python - 在 Pandas Dataframe 中查找多个字典键并返回多个匹配值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49121526/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com