【问题标题】:how to search list of dictionary values with pandas dataframe series column elements如何使用熊猫数据框系列列元素搜索字典值列表
【发布时间】:2022-01-04 14:17:31
【问题描述】:

我有一个字典和数据框列,其中包含一系列字符串类型的列表元素。

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

例如:输入

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

【问题讨论】:

  • 您在其中的任何特定部分都被卡住了吗?这是一个非常广泛的问题,只是“我如何编写这个复杂的要求”。至于问题,[grapes,are,good,for,health] 包含来自fruit_nameprofession 的字符串,哪一个获胜?此外,您的 text_column 有 4 行但是您的输出只有 3?这没有多少是可以理解的。请缩小问题的重点,包括您尝试过的代码,并使代码易于理解。
  • 请提供有效的python代码
  • @JNevill 原谅我在写作时忘记提及第 4 行输出。文本列有多个元素列表,如果在 dict 值中找到相同的元素,则应过滤它
  • @JNevill:我尝试使用 lambda 函数,但很少有元素没有被 dict 值映射/匹配/过滤。这是代码 df['text_column'].apply(lambda list: [dicts.get(item) for item in list if item in dicts.items()])
  • df['filter_values']=df['text_column'].apply(lambda list: [dicts.get(item) for item in list if item in dicts.items()])跨度>

标签: python pandas dictionary search lambda


【解决方案1】:

您可以将dict 反向创建'text_column' 中的reverse_dctmap 单词到'word_type'(顺便说一下,dict 是 Python 中的字典构造函数,不要命名你的变量 @987654327 @)。

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。如果您希望程序识别它们是相同的,则需要规范拼写。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-26
    相关资源
    最近更新 更多