python - 由索引矩阵指定的 Numpy 选择矩阵,来自多维数组
问题描述
我有一个a
大小为 numpy 的数组5x5x4x5x5
。我有另一个b
size矩阵5x5
。我想从 0a[i,j,b[i,j]]
到i
4 和j
从 0 到 4。这会给我一个5x5x1x5x5
矩阵。有没有办法做到这一点,而不仅仅是使用 2 个for
循环?
解决方案
让我们将矩阵a
视为 100(= 5 x 5 x 4)
个大小为 的矩阵(5, 5)
。所以,如果你能得到每个三元组的线性索引(i, j, b[i, j])
——你就完成了。这就是np.ravel_multi_index
进来的地方。以下是代码。
import numpy as np
import itertools
# create some matrices
a = np.random.randint(0, 10, (5, 5, 4, 5, 5))
b = np.random(0, 4, (5, 5))
# creating all possible triplets - (ind1, ind2, ind3)
inds = list(itertools.product(range(5), range(5)))
(ind1, ind2), ind3 = zip(*inds), b.flatten()
allInds = np.array([ind1, ind2, ind3])
linearInds = np.ravel_multi_index(allInds, (5,5,4))
# reshaping the input array
a_reshaped = np.reshape(a, (100, 5, 5))
# selecting the appropriate indices
res1 = a_reshaped[linearInds, :, :]
# reshaping back into desired shape
res1 = np.reshape(res1, (5, 5, 1, 5, 5))
# verifying with the brute force method
res2 = np.empty((5, 5, 1, 5, 5))
for i in range(5):
for j in range(5):
res2[i, j, 0] = a[i, j, b[i, j], :, :]
print np.all(res1 == res2) # should print True
推荐阅读
- windows - CMD 变量未在 for /r 循环中解析
- git - Go 模块用 v0.0.0 替换显式版本-
- 在 go.mod 中 - javascript - 获取mac中所有可见应用程序窗口进程的窗口标题和应用程序/进程名称
- php - php spredsheet 输出损坏的文件
- windows - 通过 openssl 创建根证书和服务器证书以在 Web 服务器上启用 https 在 Chrome 浏览器上显示 Not Secure - 所以 HTTPS 不起作用
- youtube - 我们可以在机器人框架中的视频卡上启用全屏选项吗?
- javascript - 网页登录后如何获取用户ID令牌
- redis - 如果键数量增加,Redis 性能
- android - 在应用启动时从 Web 服务加载数据
- python - 将背景颜色更改为黑色