如何使用pandasdataframeseries列元素搜索字典值列表



我有一本字典&数据帧列,它具有一系列字符串类型的列表元素。

如果字典项中的值与任何应该用项名标记的字符串元素匹配

例如:输入

text_column=[['grapes','are','good','for','health'],['banana','is','not','good','for','health'],
['apple','keeps','the','doctor','away'],['automobile','industry','is','in','top','position','from','recent','times']]
dict={ "fruit_name":['apple','grapes','lemon','cherry'],
"profession":['health','manufacturing','automobiles']
}

输出:

1) fruit_name
2) fruit_name
3) profession
4) profession

您可以反转dict,在'text_column''word_type'中创建reverse_dctmap单词(顺便说一句,dict是Python中的字典构造函数,不要将变量命名为dict(。

reverse_dct = {}
for k,v in dct.items():
for i in v:
reverse_dct[i] = k
df = pd.DataFrame({'text_column':text_column})
df['word_type'] = df['text_column'].explode().map(reverse_dct).dropna().groupby(level=0).apply(','.join)

输出:

text_column              word_type
0                   [grapes, are, good, for, health]  fruit_name,profession
1               [banana, is, not, good, for, health]             profession
2                  [apple, keeps, the, doctor, away]             fruit_name
3  [automobile, industry, is, in, top, position, ...                    NaN

请注意,最后一行没有类型,因为dict中有automobiles,但text_column中有automobile。如果你想让你的程序识别出它们是相同的,你需要规范拼写。

最新更新