且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用另一个Numpy数组设置多维Numpy数组的单个元素?

更新时间:2022-11-24 19:52:12

a 作为数据数组,将 idx 作为索引数组每行对应一个要在数据数组中设置的元素,你可以这样做 -

With a as the data array and idx as the array of indices such that each row corresponds to one element to be set in the data array, you could do -

a[tuple(idx.T)] = 5

样品运行 -

In [94]: a = np.zeros((2,2,3),dtype=int)

In [95]: idx = np.array([[0,0,0],[1,1,0],[0,1,2]])

In [96]: a[tuple(idx.T)] = 5

In [97]: a
Out[97]: 
array([[[5, 0, 0],
        [0, 0, 5]],

       [[0, 0, 0],
        [5, 0, 0]]])

In [98]: a[tuple(idx.T)] = [5,10,15] # or set different values

In [99]: a
Out[99]: 
array([[[ 5,  0,  0],
        [ 0,  0, 15]],

       [[ 0,  0,  0],
        [10,  0,  0]]])

或者,我们可以用 np来计算线性指数.ravel_multi_index 然后用 np.put 执行赋值,就像这样 -

Alternatively, we could compute the linear indices with np.ravel_multi_index and then perform the assignment with np.put, like so -

np.put(a,np.ravel_multi_index(idx.T,a.shape),5)

如果你正在处理三维数组,我们可以对三维索引进行切片并指定另一种方法,如下所示 -

If you are dealing with three dimensional arrays, we could slice the three dimensional indices and assign to have another method, like so -

a[idx[:,0],idx[:,1],idx[:,2]] = 5






如果只需要设置一个元素,只需执行 -


If it's just one element needed to be set, just do -

a[tuple(idx)] = 5

示例跑 -

In [118]: a = np.zeros((2,2,3),dtype=int)

In [119]: idx = np.array([0,0,0])

In [120]: a[tuple(idx)] = 5

In [121]: a
Out[121]: 
array([[[5, 0, 0],
        [0, 0, 0]],

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