Numpy布尔索引掩码,用于条件减去现有值

时间:2015-11-15 19:43:45

标签: python arrays numpy boolean

我在范围(0,180)中有一个数字的数字。对于每个值,如果值 x 大于90,我想用180 - x 替换它。

e.g。 5 - > 5,50 - > 50,100 - > 80,175 - > 5。

由于numpy的强大功能是它能够同时对整个阵列进行操作,例如a = a + 1将a中的所有项递增,我使用布尔掩码尝试了以下内容:

>>> import numpy as np
>>> a = np.random.randint(180, size=(20))
>>> a
array([150, 136,  28,  77,   7, 165, 114,  71, 150,  86, 129, 156,  33,
        34,  91,  87, 105,   9,   5, 108])
>>> a[a > 90] = 180 - a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: NumPy boolean array indexing assignment cannot assign 20 input values to the 10 output values where the mask is true
>>>

这会失败,因为掩码数组和原始数组的长度不匹配。 我怎么能这样做(不用手动迭代数组)?

1 个答案:

答案 0 :(得分:2)

一种方法是使用np.where

>>> a
array([172,  47,  58,  47, 162, 130,  16, 173, 125,  40,  25,  32, 123,
       142,  89,  29, 120,   2,  97, 116])
>>> np.where(a>90, 180-a, a)
array([ 8, 47, 58, 47, 18, 50, 16,  7, 55, 40, 25, 32, 57, 38, 89, 29, 60,
        2, 83, 64])

请注意,这会返回一个新数组,而不是修改现有数组。如果需要,您可以将其分配回a,但更改不会被视为&#34;引用原始数组的任何其他变量。

如果您在作业的两侧选择了适当的元素,您也可以做您所做的事情:

>>> a[a>90] = 180 - a[a>90]
>>> a
array([ 8, 47, 58, 47, 18, 50, 16,  7, 55, 40, 25, 32, 57, 38, 89, 29, 60,
        2, 83, 64])