首页 > 解决方案 > 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()])]

标签: pythonpandasnumpybitwise-operators

解决方案


是的。您正在寻找的是numpy.logical_or

conditions = [(cat == k) & (total <= v) for k, v in cutpoints.items()]
weekly_units = weekly_units[np.logical_or.reduce(conditions)]

推荐阅读