python - 如何在 Python 中基于 2D 数组对 NumPy 3D 数组进行索引?
问题描述
假设我有一个A
形状为 (66,5) 和B
形状为 (100, 66, 5) 的 NumPy 数组。
的元素A
将索引 的第一个维度 ( axis=0
) B
,其中值是从 0 到 99(即 的第一个维度B
是 100)。
A =
array([[ 1, 0, 0, 1, 0],
[ 0, 2, 0, 2, 4],
[ 1, 7, 0, 5, 5],
[ 2, 1, 0, 1, 7],
[ 0, 7, 0, 1, 4],
[ 0, 0, 3, 6, 0]
.... ]])
例如,A[4,1] 将采用 的第一个维度的索引 7、B
的第二个维度的索引 4B
和第三个维度的索引 1 B
。
我想要的是生成C
形状数组 (66,5),其中包含B
根据A
.
解决方案
你可以用它np.take_along_axis
来做到这一点:
import numpy as np
np.random.seed(0)
a = np.random.randint(100, size=(66, 5))
b = np.random.random(size=(100, 66, 5))
c = np.take_along_axis(b, a[np.newaxis], axis=0)[0]
# Test some element
print(c[25, 3] == b[a[25, 3], 25, 3])
# True
推荐阅读
- angular - Angular:使用 ngComponentOutlet 渲染组件表单
- powershell - 检查 Read-Host 是否为 Switch 的数字
- c++ - 我的向量无法访问存在的元素?
- selenium - Watir - 使用代理进行身份验证
- php - default_socket_timeout 和 mysql.connect_timeout 之间的确切关系?
- string - 如果行包含特定字符串,Notepad++ 添加新行
- excel - 检查共享工作簿是否已被其他用户打开
- linux - 可以为 linux 上的同一个应用程序同时运行 IIS 和 Apache 服务器吗?
- python-3.x - 识别 git 提交的实际分支名称
- html - 背景颜色覆盖下拉菜单 bg 颜色