【问题标题】:Using a Dictionary to filter Pandas DataFrame, where the Keys correspond to the Column Names使用字典过滤 Pandas DataFrame,其中键对应于列名
【发布时间】: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


【解决方案1】:

你可以试试:

df[(df[list(dict_example)] == list(dict_example.values())).all(axis=1)]

【讨论】:

  • 太好了,谢谢!像魅力一样工作,正是我正在寻找的东西(完成这项工作的单班轮)!
【解决方案2】:

你可以试试df.query方法

df
>>
  Col1 Col2 Col3
0    A    L    X
1    B    M    Y
2    C    N    Z  

dict_query={'Col1': 'B', 'Col2': 'M', 'Col3': 'Y'}
search_query="&".join([str(x)+"=="+"'"+str(y)+"'" for x,y in dict_query.items()])
## This is the search query
search_query
>>
Col1=='B'&Col2=='M'&Col3=='Y'

df.query(search_query)
>>
Col1    Col2    Col3
1   B   M   Y

只需使用字符串连接创建适当的查询,就可以了

【讨论】:

    猜你喜欢
    • 2013-07-01
    • 1970-01-01
    • 2015-12-22
    • 2019-01-05
    • 2017-06-06
    • 1970-01-01
    • 2017-10-28
    • 2020-07-17
    • 1970-01-01
    相关资源
    最近更新 更多