1

我有一个数组,想根据使用另一个数组的分类更改元素。

也就是说,我导入一个数组,然后如果 cell[i,j] 的值在一定范围内(比如在 1 和 8 之间),则将 secondArray[i,j] 乘以 0.3 并将结果放入输出数组中地点 [i,j]

我有一些代码可以做到这一点(并且可能更清楚地解释了我的意思)但它需要“非常”长时间(因为我的数组大约有 1000*1000 个元素)并且想知道是否有更有效的解决方案。

目前我有:

..
import numpy as np

def Factor_AM(cell):            
    if cell < 1     return 0.2;
    elif cell < 8:      return 0.3;
    else:       return 0.5;



mat = np.array(..some code to get an array from an external source..) //size 1000*1000
mat_out_1 = np.zeros_like(mat)
mat_out_1 = np.zeros_like(mat)

mat_ClassifyMe = np.array(..some code to import another 1000*1000 array with values in)

for index, x in np.ndenumerate(mat):
    mat_out_1[index] = Factor_AM(x) * mat_ClassifyMe[index]
    mat_out_2[index] = (1-Factor_AM(x)) * mat_ClassifyMe[index]

..some code to output mat_out_1 and mat_out_2

我看到一些关于 np.where 和 np.argwhere 函数的文档看起来很有希望,但鉴于我有超过 1 个测试(在上面的代码中我有 3 个但实际上我有 12 个)我想不出没有的方法制作非常难看的嵌套语句。

有没有另一种方法可以做到这一点,或者这和 Python 一样高效?

4

2 回答 2

1

为此,您可以使用布尔或“掩码”索引数组,例如:

import numpy as np

mat = np.arange(16.0).reshape((4,4))

mat_out = np.zeros_like(mat)

mat_out[mat < 6] = 0.2 * mat[mat < 6]  # using a conditional for indexing
# or use a variable for the boolean 'masking' index array
mask1 = np.logical_and(mat >= 6, mat < 10)
mat_out[mask1] = 0.3 * mat[mask1]
mask2 = mat >= 10
mat_out[mask2] = 0.5 * mat[mask2]

print mat
print mat < 6
print mask1
print mat_out
于 2013-05-08T09:59:12.073 回答
0
mat = np.array([0.1, 0.2, 5, 4, 9, 0.05, 2, 11]) # an example of input #1
mat_ClassifyMe = np.ones_like(mat) # an example of input #2
mask1 = mat < 1
mask2 = mat >= 8
f = np.empty_like(mat)
f[mask1] = 0.2
f[mask2] = 0.5
f[np.logical_not(mask1 | mask2)] = 0.3
mat_out_1 = f * mat_ClassifyMe
mat_out_2 = (1 - f) * mat_ClassifyMe
于 2017-06-28T22:37:14.803 回答