python - Numpy Where 有两个以上的条件

标签 python pandas numpy dataframe series

早上好

我有以下一个数据框,其中包含两列整数和一个计算为的系列(差异):

diff = (df["col_1"] - df["col_2"]) / (df["col_2"])

我想创建一个数据框的列,其值为:

  • 等于 0,如果 (diff >= 0) & (diff <= 0.35)
  • 等于 1,如果 (diff > 0.35)

  • 等于 2,如果 (diff < 0) & (diff >= - 0.35)

  • 等于 3,如果 (diff < - 0.35)

我试过:

df["Class"] = np.where( (diff >= 0) &  (diff <= 0.35), 0, 
np.where( (diff > 0.35), 1, 
np.where( (diff  < 0) & (diff >=  - 0.35) ), 2, 
np.where( ((diff <  - 0.35), 3) ))) 

但是报如下错误:

SystemError: <built-in function where> returned a result with an error set          

我该如何解决?

最佳答案

您可以使用 numpy.select分别指定条件和值。

s = (df['col_1'] / df['col_2']) - 1

conditions = [s.between(0, 0.35), s > 0.35, s.between(-0.35, 0), s < -0.35]
values = [0, 1, 2, 3]

df['Class'] = np.select(conditions, values, np.nan)

关于python - Numpy Where 有两个以上的条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51301149/

相关文章:

python - 如何在 Python 中对数据框进行分组并汇总连续数字的子组?

python - 在单列上使用 `apply` 加速分组

python - 使用 Tkinter/ttk 垂直展开一个小部件,同时锁定另一个小部件

python - 在没有其他低级库的情况下使用 Python 监视文件系统事件

python-3.x - 通过最接近的匹配合并不同长度的两列上的两个 Dataframe

Python 3 - ValueError : Found array with 0 sample(s) (shape=(0, 11)) 而 MinMaxScaler 要求至少为 1

python - matplotlib 不生成 PS 输出

python - 如何将pygame中的3d数组转换为opencv python中的有效输入?

python - pybind 如何操作 py::list 对象

python - 如何从 process.Popen() 引发事件 getche() - 不监视标准输入