numpy.where具有多个条件

2024-09-28 03:18:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我在这里是因为我有一个关于函数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)

我发现np.where在有一个条件时有效(例如,低于-1.5的等级和高于11的等级),但如果有两个不同的条件(例如,这个:np.where(等级>;=1和等级<;3,2,等级))则不起作用

你知道我怎样才能解决这个问题吗

多谢各位


Tags: and函数程序numpynp数组where条件
3条回答

您使用的逻辑运算符and不适用于数组操作。改为使用逐元素操作的位运算符

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

看看这个:link

另一种方法是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]

输出:

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

这是np.select()函数的一个很好的例子The docs can be found here

设置很简单:

  • 创建list丹麦系统等级
  • 创建list个映射。下面的案例使用逻辑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)]

用法:
调用np.select函数并传入上面创建的两个列表

# Map grades to Danish system.
np.select(condlist=scale, choicelist=grades)

输出:

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

相关问题 更多 >

    热门问题