python - 按字典键值对过滤熊猫数据框
问题描述
有没有更优雅的方法来按一列过滤数据框,然后为每个子集进一步过滤另一列?并将结果数据放在一个数据框中?过滤信息在字典中。第一个过滤器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 |
解决方案
使用 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
推荐阅读
- sql-server - 使用带有版本控制的 MVC .net 更新 SQL Server 数据库架构
- javascript - Javascript -> symfony 控制器请求
- python - Python async functions
- c - 如果每个需要的库都包含在我的 main 中,我是否需要在具有函数实现的文件中 #include 任何内容?
- python - Python正则表达式从具有各种结构的文件中提取数据
- javascript - 在使用 Scully 的现有应用程序上生成角度静态 html 时出错
- c - 在格式规范之前使用逗号。在 C 中的 scanf 中?
- javascript - 如何在 PhpStorm 的 JavaScript 中启用 Emmet?
- python - PySide2:AttributeError:“NoneType”对象没有属性“objectName”
- python - 测试 SQLAlchemy 会话是否已关闭