首页 > 解决方案 > numpy.where 有多个条件

问题描述

我在这里是因为我对函数 numpy.where 有疑问。我需要开发一个程序,以丹麦评分标准对学生的成绩进行四舍五入。

(丹麦评分标准是从最好的(12)到最差的(-3)的 7 个等级:12 10 7 4 02 00 -3)

这是成绩的数组:

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)

我发现 np.where 在有一种条件时有效(例如,低于 -1.5 的成绩和超过 11 的成绩有效)但如果有 2 种不同的条件(例如这个:np.where(grades> =1 和等级<3, 2, 等级))它不会工作。

你知道我怎么能解决这个问题吗?

非常感谢。

标签: pythonfunctionnumpywhere-clause

解决方案


and您正在使用不适用于数组操作的逻辑运算符。改用按位运算符来逐个元素地操作。

np.where((grades>=1) & (grades<3), 2, grades))

看看这个:链接


推荐阅读