如何在 numpy 的条件下用其列或行索引替换值?

How to replace value with its column or rows index on condition in numpy?

如果值 >= 1,如何用列索引替换 n x n 数组中的每个值,否则用行索引。 如果替换值将映射到其他一维数组并且 return 来自它的值,那就更好了。

value_array = np.array([200, 200, 300, 10])

arr = np.array(
  [[1, 1, .66, 20],
   [1, 1, .66, 20],
   [1.5, 1.5, 1, 30],
   [.05, .05, .03, 1]]
)

目标是获得一个大小相同的数组,其中包含来自 value_array 的值。 示例:

此外,这要应用于大数组 (1m x 1m) 执行需要以某种方式分成多个部分。

使用numpy.select的一种方式:

conds = [arr>1, arr<1]
target = np.full(arr.shape, value_array)
np.select(conds, [target, target.T], arr)

输出:

array([[  1.,   1., 200.,  10.],
       [  1.,   1., 200.,  10.],
       [200., 200.,   1.,  10.],
       [ 10.,  10.,  10.,   1.]])

使用 np.where 的另一个选项:

# I've rename value_array to v for simplicity.
# We use the broadcasting potential of numpy to get our result
res = np.where(arr>=1,v,v.reshape(len(v),1))

res=

array([[200, 200, 200,  10],
       [200, 200, 200,  10],
       [200, 200, 300,  10],
       [ 10,  10,  10,  10]])

此解决方案还使用较少的内存,因为您不需要存储中间结果。