如何基于2D索引和1D值向量替换Numpy 3D数组中沿z轴的值
问题描述:
我似乎很难理解数组索引.
I'm struggling to understand array indexing it seems.
给出的内容:
我确实有一个3d数组,如下所示:
I do have a 3d array like so:
a_3d = np.zeros((3,3,3))
二维索引数组:
a_2d_index = np.array([[0,0,1], [0,0,0], [0,1,1]]).astype('bool')
以及要放置到x,y位置的3d数组中的值:
And values to place into 3d array at x,y location:
a_1d_fill = np.array([10,20,30])
现在,我想使用a_2d_index在a_3d中查找位置,并将a_1d_fill垂直放置在此x,y位置...
Now, I do want to use a_2d_index to find the locations in a_3d and vertically place the a_1d_fill at this x,y position...
最终结果应如下所示:
a_3d := [[[0,0, 10],
[0,0, 0],
[0,10,10]],
[[0,0, 20],
[0,0, 0],
[0,20,20]],
[[0,0, 30],
[0,0, 0],
[0,30,30]]]
这将用于非常大的阵列,因此内存效率和速度至关重要……(少量复制,最好是就地修改)
This will be used on very large array so memory efficiency and speed are crucial... (little copying, preferably in-place modification)
答
In [26]: a_3d = np.zeros((3,3,3), dtype=int)
In [27]: a_2d_index = np.array([[0,0,1], [0,0,0], [0,1,1]]).astype('bool')
In [28]: a_1d_fill = np.array([10,20,30])
In [29]: a_3d[:,a_2d_index] = a_1d_fill[:,np.newaxis]
In [30]: a_3d
Out[30]:
array([[[ 0, 0, 10],
[ 0, 0, 0],
[ 0, 10, 10]],
[[ 0, 0, 20],
[ 0, 0, 0],
[ 0, 20, 20]],
[[ 0, 0, 30],
[ 0, 0, 0],
[ 0, 30, 30]]])