【发布时间】: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