python - 使用数组作为多维数组的索引掩码

标签 python numpy

我有以下数组:

a = np.arange(12).reshape((2, 2, 3))

b = np.zeros((2, 2))

现在我想用b访问a,s.t。对于索引 i,j,如果 b[i, j] = z,则我们取 a 的第 z 个元素。 对于上面的例子来说,答案应该是 [[0, 3], [6, 9]]。 我觉得这与 np.choose 非常相关,但不知何故无法完全管理它。 你能帮我吗?

最佳答案

可以建议两种方法。

使用显式范围数组 advanced-indexing -

m,n = b.shape
out = a[np.arange(m)[:,None],np.arange(n),b.astype(int)]

np.take_along_axis -

np.take_along_axis(a,b.astype(int)[...,None],axis=2)[...,0]

示例运行 -

In [44]: a
Out[44]: 
array([[[ 0,  1,  2],
        [ 3,  4,  5]],

       [[ 6,  7,  8],
        [ 9, 10, 11]]])

In [45]: b
Out[45]: 
array([[0., 0.],
       [0., 0.]])

In [46]: m,n = b.shape

In [47]: a[np.arange(m)[:,None],np.arange(n),b.astype(int)]
Out[47]: 
array([[0, 3],
       [6, 9]])

In [48]: np.take_along_axis(a,b.astype(int)[...,None],axis=2)[...,0]
Out[48]: 
array([[0, 3],
       [6, 9]])

关于python - 使用数组作为多维数组的索引掩码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55605833/

相关文章:

python - 从 EXPLOSM.net 漫画脚本下载 [Python]

python - 基于目标变量的编码技术预测看不见的数据

python - 在企业防火墙后面验证谷歌云

python - 获取与指定签名和转换错误匹配的无循环

python - 在 Python 中处理 pandas DataFrames 列划分中的零

python - 我正在尝试实现有效的正则表达式模式

python - 计算满足条件的连续值的数量(Pandas Dataframe)

python - python中将字符串与numpy数组中的格式化数字转换的最快方法是什么

python-3.x - Numpy 计算随机 2D 或 1D 数组中的 Min Max

python - 根据行号删除数据帧的行