Python-过滤包含字典中特定键的任何值的数据框

时间:2018-11-07 15:20:19

标签: python pandas dictionary dataframe filter

我遇到了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方法。但这给了我一个“无法散列的类型:'列表'”错误。

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

1 个答案:

答案 0 :(得分:0)

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

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

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

然后将其用作过滤条件。

df[df['col2'].str.contains(search_list)]
相关问题