Python np.select 不遵守我的条件,为什么?

Python np.select does not obey my conditions, why?

我有这部分代码:

title = "Margin with minimal market price"

active_prods[title] = (active_prods['market min'] - active_prods['cost']) / active_prods['market min']

conditions = [
    (active_prods[title] < 0),
    (active_prods[title] >= 0) & (active_prods[title] <= 5),
    (active_prods[title] > 5) & (active_prods[title] <= 10)]
choices = ['1) <0', '2) <=5%', '3) <=10%']
active_prods['Margin type'] = np.select(conditions, choices, default='4) >10%')

长话短说 - 我正在尝试计算我的产品利润并根据它在间隔中的位置为其提供某种类型。我的代码正确设置了所有 <0 边距,但是大于或等于零的所有内容都设置为第二个选项:

2) <=5%

不知何故它只接受第二个条件的第一部分(>=0)而完全忽略条件的第二部分。第三个条件也完全忽略了。为什么会这样?

Active_prods 是 pandas 数据帧。

这是实现它的另一种方法。您可以使用 bin 并将范围切割成篮子。 请参阅下面的模型:

import pandas as pd
active_prods = pd.DataFrame({'Margin':[0,-2,4,10,35,1,54]})
bins= [-100,0,6,11,100]
labels = ['1) <0','2) <=5%','3) <=10%','4) >10%']
active_prods['MarginType'] = pd.cut(active_prods['Margin'], bins=bins, labels=labels, right=False)
active_prods

查看以下结果:

Margin  MarginType
0   0   2) <=5%
1   -2  1) <0
2   4   2) <=5%
3   9   3) <=10%
4   35  4) >10%
5   1   2) <=5%
6   54  4) >10%

假设 active_prods 是一个 Numpy 数组,我认为你的 & 对于组合逻辑数组是不正确的。

你可能想要:

np.logical_and(active_prods[title] >= 0, active_prods[title] <= 5)