多元 numpy 数组中的索引

Indexing in multl-dimentional numpy array

提问人:Raina ZHANG 提问时间:11/16/2023 更新时间:11/16/2023 访问量:37

问:

提前感谢您的帮助!

我有一个 4D numpy 数组

a = np.random.random_integers(1,5,(2,3,3,4))
>>> a
array([[[[5, 2, 5, 3],
         [1, 3, 1, 2],
         [4, 3, 1, 2]],

        [[3, 1, 3, 5],
         [2, 5, 2, 3],
         [1, 4, 1, 3]],

        [[4, 2, 4, 3],
         [1, 3, 5, 2],
         [3, 5, 4, 4]]],


       [[[1, 1, 2, 3],
         [2, 1, 5, 3],
         [1, 5, 5, 4]],

        [[1, 2, 3, 3],
         [5, 2, 4, 3],
         [4, 3, 4, 5]],

        [[4, 3, 5, 3],
         [3, 5, 2, 4],
         [4, 3, 3, 1]]]])

我有一个 3D numpy 数组 b,它与 a 的最后三个维度的形状相同,由 0 和 1 组成。

b = np.random.random_integers(0,1,(3,3,4))
>>> b
array([[[0, 0, 0, 0],
        [0, 0, 0, 1],
        [1, 0, 1, 0]],

       [[0, 1, 1, 0],
        [1, 1, 0, 1],
        [1, 1, 0, 1]],

       [[0, 0, 0, 1],
        [0, 1, 1, 0],
        [1, 0, 1, 0]]])

对于 a 中的每个 (3, 3, 4) 数组,我想在数组 b 的相同位置选择值为 1 的元素,并根据另一个数组 c 更新这些值,该数组 c 的形状为 a 的第一维:

c = np.array([-1, -2])

因此,在数组 b 中值为 1 的 a[0,:] 中的值将变为 -1 (c[0])

和 a[1,:] 中的值。在数组 B 中值为 1 的将变为 -2 (c[1])

最终,我想以一种有效的方式获得一个与具有更新值的数组具有相同形状的数组

>>> return 
array([[[[5, 2, 5, 3],
         [1, 3, 1, -1],
         [-1, 3, -1, 2]],

        [[3, -1, -1, 5],
         [-1, -1, 2, -1],
         [-1, -1, 1, -1]],

        [[4, 2, 4, -1],
         [1, -1, -1, 2],
         [-1, 5, -1, 4]]],


       [[[1, 1, 2, 3],
         [2, 1, 5, -2],
         [-2, 5, -2, 4]],

        [[1, -2, -2, 3],
         [-2, -2, 4, -2],
         [-2, -2, 4, -2]],

        [[4, 3, 5, -2],
         [3, -2, -2, 4],
         [-2, 3, -2, 1]]]])
numpy 多维数组 索引

评论


答:

0赞 RomanPerekhrest 11/16/2023 #1

以直截了当的方式:

for i in range(a.shape[0]):
    a[i][np.where(b)] = c[i]

print(a)

[[[[ 5  2  5  3]
   [ 1  3  1 -1]
   [-1  3 -1  2]]

  [[ 3 -1 -1  5]
   [-1 -1  2 -1]
   [-1 -1  1 -1]]

  [[ 4  2  4 -1]
   [ 1 -1 -1  2]
   [-1  5 -1  4]]]


 [[[ 1  1  2  3]
   [ 2  1  5 -2]
   [-2  5 -2  4]]

  [[ 1 -2 -2  3]
   [-2 -2  4 -2]
   [-2 -2  4 -2]]

  [[ 4  3  5 -2]
   [ 3 -2 -2  4]
   [-2  3 -2  1]]]]
1赞 mozway 11/16/2023 #2

使用 broadcasting 和 numpy.where

tmp = b[None] * c[:,None,None,None]
out = np.where(tmp, tmp, a)

或者(归功于@Chrysophylaxs):

out = np.where(b, c[:, None, None, None], a)

或者,要分配给:a

tmp = b[None] * c[:,None,None,None]
m = tmp!=0
a[m] = tmp[m]

输出:

array([[[[ 5,  2,  5,  3],
         [ 1,  3,  1, -1],
         [-1,  3, -1,  2]],

        [[ 3, -1, -1,  5],
         [-1, -1,  2, -1],
         [-1, -1,  1, -1]],

        [[ 4,  2,  4, -1],
         [ 1, -1, -1,  2],
         [-1,  5, -1,  4]]],


       [[[ 1,  1,  2,  3],
         [ 2,  1,  5, -2],
         [-2,  5, -2,  4]],

        [[ 1, -2, -2,  3],
         [-2, -2,  4, -2],
         [-2, -2,  4, -2]],

        [[ 4,  3,  5, -2],
         [ 3, -2, -2,  4],
         [-2,  3, -2,  1]]]])

评论

1赞 Chrysophylaxs 11/16/2023
np.where(b, c[:, None, None, None], a):)
1赞 mozway 11/16/2023
@Chrysophylaxs不错的一个;)