按字典键值对筛选数据帧

2024-04-19 16:49:28 发布

您现在位置:Python中文网/ 问答频道 /正文

是否有一种更优雅的方法可以按一列过滤数据帧,然后按另一列进一步过滤每个子集?结果数据是否在一个数据帧中?过滤信息在字典中。第一个过滤器在使用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   |

Tags: 数据方法信息过滤器dataframedfnew字典
1条回答
网友
1楼 · 发布于 2024-04-19 16:49:28

用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

相关问题 更多 >