如何基于2D索引和1D值向量替换Numpy 3D数组中沿z轴的值 [英] How do I replace values along z-axis in Numpy 3D array based on 2D index and 1D value vector

查看:86
本文介绍了如何基于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]]])

这篇关于如何基于2D索引和1D值向量替换Numpy 3D数组中沿z轴的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆