Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/341.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用矢量化函数重新分类numpy浮点数组时出现广播错误_Python_Numpy_Broadcast_Array Broadcasting - Fatal编程技术网

Python 使用矢量化函数重新分类numpy浮点数组时出现广播错误

Python 使用矢量化函数重新分类numpy浮点数组时出现广播错误,python,numpy,broadcast,array-broadcasting,Python,Numpy,Broadcast,Array Broadcasting,我想计算2D numpy浮点数组中的每个值,如果它位于某个数值类的最小、最大边界内。接下来,我想将该值重新分配给与该类关联的“分数” 例如,阶级界限可以是: >>> class1 = (0, 1.5) >>> class2 = (1.5, 2.5) >>> class3 = (2.5, 3.5) 班级成绩如下: >>> score1 = 0.75 >>> score2 = 0.50 >>>

我想计算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,) 
>>将numpy作为np导入
>>>arr_f=(6-0)*np.random.random_样本((4,4))+0#随机浮点数组
>>>def重分类器(x、类、新闻):
>>>比较=[x>=min和x>>尝试:
>>>返回新闻[比较索引(True)
>>>除值错误外:
>>>返回99.0
>>>v_func=np.矢量化(重分类器)
>>>out=v_func(arr_f,[class1,class2,class3],[score1,score2,score3])
ValueError:操作数无法与形状(4,4)(4,2)(4,)一起广播

任何关于此错误发生的原因以及如何纠正的建议都将不胜感激。此外,如果我使用矢量化函数完全走错了路,我也很高兴听到这一点。

尝试在不使用
np.vectorize
的情况下首先使代码工作。上面的代码即使使用单个浮点作为第一个参数也无法工作。您错了拼写为
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

分数
将是一个与原始数据数组相对应的分数数组。

谢谢,这工作完美无瑕!我曾想过使用字典将范围和分数配对,但不知何故,我认为元组和列表一样,不能作为字典键。逻辑是元组是不可变的,因此对它们进行散列更有意义因为它们是可散列的,所以可以用作dict键。
# 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