字典中的完全匹配词'键'到Pandas DataFrame列并返回适当的值

问题描述 投票:0回答:2

只是想序言这个问题是从我之前的问题演变而来的,可以找到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将如何匹配“最便宜”,池将匹配“利物浦”

所以我的问题是:我有没有办法让我的字典与关键字中的值完全匹配,以便跳过部分匹配?

我期望的结果是:

                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'}这就是为什么我想完全匹配以防止出现任何重复/不相关的值。

干杯

python pandas dictionary textmatching
2个回答
1
投票

这是我的第一个解决方案。 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)

结果

               keywords          values
0  cheapest cheap shoes          budget
1          luxury shoes       expensive
2    cheap hiking shoes  budget | sport
3             liverpool                

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
© www.soinside.com 2019 - 2024. All rights reserved.