【发布时间】:2021-09-10 22:00:53
【问题描述】:
我正在尝试使用字典的值来“过滤” Pandas DataFrame,其中字典的键对应于 DataFrame 中的列。
例子:
In [5]: df
Out[5]:
Col1 Col2 Col3
0 A L Y
1 B M Y
2 B N Z
In [7]: dict_example
Out[7]: {'Col1': 'B', 'Col2': 'M', 'Col3': 'Y'}
根据 dict_example 中的值,我想要的结果只是第二行,
Out[5]:
Col1 Col2 Col3
1 B M Y
我尝试过这样的事情:
In [8]: df[df.isin(dict_example.values())]
Out[8]:
Col1 Col2 Col3
0 NaN NaN Y
1 B M Y
2 B NaN NaN
但它给了我整个 DataFrame,而不仅仅是行,其中字典中的所有值都对应于 DataFrame 中的值。
我当然可以这样做:
In [9]: df[(df['Col1']=='B')&(df['Col2']=='M')&(df['Col3']=='Y')]
Out[9]:
Col1 Col2 Col3
1 B M Y
但这变得越来越困难,您需要过滤的维度越多。
如果有任何意见,我将不胜感激!
【问题讨论】:
-
df[df.isin(dict_example.values())] .dropna()??
标签: python pandas dataframe dictionary filter