按字典键值对过滤熊猫数据帧

时间:2020-04-13 19:22:19

标签: python pandas

是否存在一种更优雅的方法来按一列过滤数据帧,然后对每个子集进一步过滤另一列?并将结果数据放在一个数据帧中吗?过滤信息在字典中。第一个过滤器使用dict键位于col1上。第二个过滤器使用相应的值位于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   |

1 个答案:

答案 0 :(得分:3)

使用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