且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-05-04 10:03:22

当然有可能.这是一种方法.

It's certainly possible. Here is one way.

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