如何根据条件有效地更改numpy数组元素

时间:2018-10-24 11:27:49

标签: python arrays numpy python-3.6

我有一个3维uint8 numpy数组。我想将所有具有以下值的元素增加1:0、1、3、16、17、18。并将其他设置为0。我尝试使用传统的for循环,这真的很慢。

尝试使用python索引技术将其他值设置为255(稍后将更改为0)

mask[(mask[:,:,:] != 0) & (mask[:,:,:] != 1) & (mask[:,:,:] != 3) & (mask[:,:,:] != 16) & (mask[:,:,:] != 17) & (mask[:,:,:] != 18)] = 255

然后将值增加1

mask[(mask[:,:,:] == 0) & (mask[:,:,:] == 1) & (mask[:,:,:] == 3) & (mask[:,:,:] == 16) & (mask[:,:,:] == 17) & (mask[:,:,:] == 18)] = mask[:,:,:]+1 #gives me error

然后将255更改为0

mask[mask[:,:,:] == 255] = 0

中间操作给我错误

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

如何有效地做到这一点。最好一口气。不是3次遍历数组。

1 个答案:

答案 0 :(得分:3)

使用np.isin,然后使用布尔索引将值更改为:

arr = np.arange(0,255)
mask = np.isin(arr,[0,1,3,16,17,18])

arr[mask]+=1
arr[~mask]=0

或将np.where用作:

arr = np.where(np.isin(arr,[0,1,3,16,17,18]),arr+1,0)

arr
array([ 1,  2,  0,  4,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 17,
       18, 19,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
        0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
        0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
        0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
        0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
        0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
        0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
        0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
        0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
        0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
        0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
        0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
        0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
        0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0])