首页 > 解决方案 > 按字典键值对过滤熊猫数据框

问题描述

有没有更优雅的方法来按一列过滤数据框,然后为每个子集进一步过滤另一列?并将结果数据放在一个数据框中?过滤信息在字典中。第一个过滤器col1使用 dict 键。第二个过滤器正在col3使用其相应的值。

df = pd.DataFrame({'col1': [1,1,1,2,2], 'col2': [2,2,2,2,2], 'col3': [1,6,7,5,9]})

df如下所示

    |col1|col2|col3|
    |1   |2   |1   |
    |1   |2   |6   |
    |1   |2   |7   |
    |2   |2   |5   |
    |2   |2   |9   |

filter_dict = {1:5, 2:7}

df_new = df.somefunction(filter_dict)

哪里col1是 1,过滤col3值大于 5。哪里col1是 2,过滤col3值大于 7。这将导致:

df_new

    |col1|col2|col3|
    |1   |2   |6   |
    |1   |2   |7   |
    |2   |2   |9   |

标签: pythonpandas

解决方案


使用 concat 进行列表理解和布尔索引

df_new = pd.concat([df[(df['col1'] == k) & (df['col3'] > v)] for k,v in filter_dict.items()])

   col1  col2  col3
1     1     2     6
2     1     2     7
4     2     2     9

推荐阅读