我想评估2D numpy浮点数组中的每个值,如果它落在某个数值类的最小,最大边界内。接下来,我想将该值重新分配给与该类关联的“得分”。
例如,类边界可以是:
>>> class1 = (0, 1.5)
>>> class2 = (1.5, 2.5)
>>> class3 = (2.5, 3.5)
课程成绩如下:
>>> score1 = 0.75
>>> score2 = 0.50
>>> score3 = 0.25
任何类之外的值应默认为例如99。
我尝试了以下内容,但由于广播而遇到了ValueError。
>>> import numpy as np
>>> arr_f = (6-0)*np.random.random_sample((4,4)) + 0 # array of random floats
>>> def reclasser(x, classes, news):
>>> compare = [x >= min and x < max for (min, max) in classes]
>>> try:
>>> return news[compare.index(True)
>>> except Value Error:
>>> return 99.0
>>> v_func = np.vectorize(reclasser)
>>> out = v_func(arr_f, [class1, class2, class3], [score1, score2, score3])
ValueError: operands could not be broadcast together with shapes (4,4) (4,2) (4,)
有关此错误发生原因以及如何修复的任何建议将非常感激。此外,如果我使用矢量化函数完全走错路径,我也很乐意听到。
尝试首先使代码工作,而不使用np.vectorize
。即使使用单个float作为第一个参数,上面的代码也不会起作用。你拼错了ValueError
;使用min
和max
作为变量名称(它们是Python函数)也不是一个好主意。固定版本的reclasser
将是:
def reclasser(x, classes, news):
compare = [min(cls) < x < max(cls) for cls in classes]
try:
return news[compare.index(True)]
except ValueError:
return 99.0
也就是说,我认为使用reclasser和np.vectorize
是不必要的复杂。相反,你可以这样做:
# class -> score mapping as a dict
class_scores = {class1: score1, class2: score2, class3: score3}
# matrix of default scores
scores = 99 * np.ones(arr_f.shape)
for cls, score in class_scores.items():
# see which array values belong into current class
in_cls = np.logical_and(cls[0] < arr_f, arr_f < cls[1])
# update scores for current class
scores[np.where(in_cls)] = score
然后scores
将是对应于原始数据阵列的分数数组。