Python numpy.where具有多个条件

Python numpy.where具有多个条件,python,function,numpy,where-clause,Python,Function,Numpy,Where Clause,我在这里是因为我有一个关于函数numpy.where的问题。 我需要开发一个程序,用丹麦评分表对学生的成绩进行评分 (丹麦评分标准为7级,从最好的(12)到最差的(-3):1210740200−(三) 以下是等级数组: grades=np.array([[-3,-2,-1,0],[1,2,3,4],[5,6,7,8],[9,10,11,12]]) 我想做的是: gradesrounded=np.where(grades<-1.5, -3, grades) gradesrounded=np

我在这里是因为我有一个关于函数numpy.where的问题。 我需要开发一个程序,用丹麦评分表对学生的成绩进行评分

(丹麦评分标准为7级,从最好的(12)到最差的(-3):1210740200−(三)

以下是等级数组:

grades=np.array([[-3,-2,-1,0],[1,2,3,4],[5,6,7,8],[9,10,11,12]])
我想做的是:

gradesrounded=np.where(grades<-1.5, -3, grades)
gradesrounded=np.where(-1.5<=grades and grades<1, 0, grades)
gradesrounded=np.where(grades>=1 and grades<3, 2, grades)
gradesrounded=np.where(grades>=3 and grades<5.5, 4, grades)
gradesrounded=np.where(grades>=5.5 and grades<8.5, 7, grades)
gradesrounded=np.where(grades>=8.5 and grades<11, 10, grades)
gradesrounded=np.where(grades>=11, 12, grades)
print(gradesrounded)

gradesrounded=np。其中(grades您使用的逻辑运算符
不适用于数组操作。请改用逐元素操作的位运算符


np.where((grades>=1)和(grades如果要将其作为字符串,还可以使用pandas数据帧和查询函数。以下是一个示例:

df = df.query('grades>=1 & grades<3')

df=df.query('grades>=1&grades这是
np.select()函数的一个很好的例子

设置很简单:

  • 创建丹麦系统等级的
    列表
  • 创建映射的
    列表
    。下面的案例使用逻辑and
    &
    运算符链接多个条件
设置:

import numpy as np

# Sample grades.
x = np.array([-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])

# Define limits and lookup.
grades = [12, 10, 7, 4, 2, 0, -3]
scale = [(x >= 11), 
         (x >= 8.5) & (x < 11),
         (x >= 5.5) & (x < 8.5),
         (x >= 3.0) & (x < 5.5),
         (x >= 1.0) & (x < 3.0),
         (x >= -1.5) & (x < 1.0 ),
         (x < -1.5)]
输出:

array([-3, -3,  0,  0,  2,  2,  4,  4,  4,  7,  7,  7, 10, 10, 12, 12])

另一种方法是
np.searchsorted

scales = np.array([-3,0,2,4,7,10,12])

grades=np.array([[-3,-2,-1,0],[1,2,3,4],[5,6,7,8],[9,10,11,12]])

thresh = [-1.5, 0.5 ,2.5,5.5,8.5,10]
out = scales[np.searchsorted(thresh, grades)]

# or
# thresh = [-3, -1.5, 1, 3, 5.5, 8.5, 11]
# out = scales[np.searchsorted(thresh, grades, side='right')-1]
输出:


对不起,丹麦的评分是什么!?非常感谢:)
scales = np.array([-3,0,2,4,7,10,12])

grades=np.array([[-3,-2,-1,0],[1,2,3,4],[5,6,7,8],[9,10,11,12]])

thresh = [-1.5, 0.5 ,2.5,5.5,8.5,10]
out = scales[np.searchsorted(thresh, grades)]

# or
# thresh = [-3, -1.5, 1, 3, 5.5, 8.5, 11]
# out = scales[np.searchsorted(thresh, grades, side='right')-1]
array([[-3, -3,  0,  0],
       [ 2,  2,  4,  4],
       [ 4,  7,  7,  7],
       [10, 10, 12, 12]])