如何使用另一个 Numpy 数组设置多维 Numpy 数组的单个元素? [英] How to set single element of multi dimensional Numpy Array using another Numpy array?
问题描述
如果我们有一个像这样的 numpy 数组:
If we have a numpy array like:
Array = np.zeros((2, 10, 10))
我们想设置它的一个元素,由另一个给定
and we want to set one element of it, given by another
indexes = np.array([0,0,0])
我们该怎么做?
Array[indexes] = 5
正在将数组的第一个维度的每个元素设置为 5
is setting every element of the FIRST dimension of Array to 5
推荐答案
以 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]]])
这篇关于如何使用另一个 Numpy 数组设置多维 Numpy 数组的单个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!