【问题标题】:Python - Filter a Dataframe that contains any of the values for a specific key in a dictionary [duplicate]Python - 过滤包含字典中特定键的任何值的数据框[重复]
【发布时间】:2019-04-11 01:23:06
【问题描述】:

我在使用 python pandas 时遇到问题,如果特定列包含我的字典中特定键的任何值,我想过滤数据框。

In  [1]: import pandas as pd
         data = {'col1': ['123apple645', '654banana213', '987orange815'], 
                 'col2': ['345mango987', '159peach357', '852apple258'], 
                 'col3':['654apple789', '324peach156', '358grapes854']}
         df = pd.DataFrame(data=data)
         dictionary = {'Mary':['apple', 'peach'], 'John':['peach', 'grapes']}

Out [1]:    col1            col2            col3
        0   123apple645     345mango987     654apple789
        1   654banana213    159peach357     324peach156
        2   987orange815    852apple258     358grapes854

如果第 2 列包含字典中键“John”的任何值,我想过滤它。所以结果应该只返回索引 1,因为这是唯一的行,其值包含与 John 的键对应的任何值。

In  [2]: ???

Out [2]:    col1            col2            col3
        1   654banana213    159peach357     324peach156

我的尝试是使用 .str.contains 方法。但这给了我一个“不可散列的类型:'list'”错误。

Filtered_df = df[df['col2'].str.contains(dictionary['John'])]

【问题讨论】:

    标签: python pandas dictionary dataframe filter


    【解决方案1】:

    我从这里找到了答案:Pandas filtering for multiple substrings in series

    解决方案是首先使用或(“|”)运算符连接搜索列表。

    search_list = '|'.join(dictionary['John'])
    

    然后将其应用为过滤条件。

    df[df['col2'].str.contains(search_list)]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-14
      • 2020-04-28
      • 2020-12-17
      • 2019-06-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多