python - Python/Pandas 中按位运算符的 any() 和 all() 类似物
问题描述
我有一个带有“Category”和“Total”列的 pandas DataFrame。可以有 4 个不同的类别:A、B、C、D。我被赋予每个类别的切点值作为 dict。我需要排除 Total 超过相应切点的所有条目。这工作正常:
cat = weekly_units['Category']
total = weekly_units['Total']
weekly_units = weekly_units[(cat == 'A') & (total <= cutpoints['A'])
| (cat == 'B') & (total <= cutpoints['B'])
| (cat == 'C') & (total <= cutpoints['C'])
| (cat == 'D') & (total <= cutpoints['D'])]
但我发现它湿且不合常规。有没有办法写这样的东西?
weekly_units = weekly_units[any([(cat == k) & (total <= v) for k, v in cutpoints.items()])]
解决方案
是的。您正在寻找的是numpy.logical_or
:
conditions = [(cat == k) & (total <= v) for k, v in cutpoints.items()]
weekly_units = weekly_units[np.logical_or.reduce(conditions)]
推荐阅读
- vue.js - 故事书代码预览不显示 VueJS 中插槽的使用情况
- sql - 在两个新列中显示数据
- python - 将一组元组转换为列表列表 | Python
- python-3.x - 如何在需要在范围外使用变量时在 if 语句中获取此输入语句以进行提示?
- javascript - 为什么这个块不折叠?
- javascript - 在 React Native 中创建 Carousel,如示例图像
- c# - 如何将数据插入到 .NET Core API 中的多个相关表中?
- probability - 时间相关的分散内核
- c# - 从 ModalAsync 更新 ObservableCollection
- go - 你好,我正在为 golang 学习 fyne.io,我遇到了一个问题