Pandas 和 NLTK:如果 NLTK 标记中包含子字符串,则用相邻列的子字符串替换空单元格

Pandas and NLTK: Replace empty cells with subsring of adjacent column, if substring is contained in NLTK tokens

我有一个 table 由产品名称和制造商组成。一些制造商单元格是空的,因此我想编写一个代码来用产品名称中的子字符串替换制造商列中的空单元格。这是 table 的信息:

为了识别我要使用的子字符串,我使用了 NLTK 库。

这是我到目前为止编写的代码:

import pandas as pd
import nltk
from nltk.probability import FreqDist
import pandas as pd
import numpy as np


a=('Nokia 3518','Nokia 3313','Samsung S9','Samsung S10','Samsung S4')
b=('Nokia','','','Samsung','')

df=pd.DataFrame({'Product Name':(a) , 'Maker':(b)})
df.replace('', np.nan, inplace=True)


result = [' '.join([row for row in df['Product Name']])]

result=str(result).replace("'",'')

tokens = nltk.word_tokenize(result)
#iam taking only words greater than 4 letters

longwords= [wrd for wrd in tokens if len(wrd)>4] #Words containing 3 letters or less will be 
removed

print(longwords)

#keeping words only that occur more than once and putting it in a dataframe
fdist = FreqDist(longwords)
x=list(filter(lambda x: x[1]>1,fdist.items())) 
print(x)

# putting the tokens in a dataframe (Nokia and Samsung)
dfb=pd.DataFrame(x)

print(dfb[0])

到目前为止,我已经编写了生成令牌的代码,但是我不确定如何从这里继续。

最后,我想通过允许代码将产品名称中的子字符串与令牌数据框 (dfb) 中的项目相匹配并相应地附加制造商列来附加如下数据框:

这是我发现添加到原始代码中的最简单的答案::

z=[]
for i in df['Product Name']:
    for j in dfb[0]:
        if j in i:
            z.append(j)

df['Maker']=z

print(df)