python - 从索引矩阵向量化数组访问
问题描述
考虑以下:
In [51]: arr = np.arange(6, 10)
In [52]: idx = np.random.randint(4, size=(3, 4))
In [53]: idx
Out[53]:
array([[0, 3, 3, 1],
[1, 3, 3, 2],
[1, 1, 1, 1]])
In [54]: result = np.empty_like(idx)
In [55]: for i in range(idx.shape[0]):
...: result[i] = arr[idx[i]]
...:
In [56]: result
Out[56]:
array([[6, 9, 9, 7],
[7, 9, 9, 8],
[7, 7, 7, 7]])
如何矢量化for
循环?我找不到通过索引矩阵“多次”访问一维数组的方法,其中每行都是索引数组。
解决方案
arr
如评论中所述,您可以使用数组简单地索引到idx
数组。
In [47]: arr
Out[47]: array([6, 7, 8, 9])
In [48]: idx
Out[48]:
array([[3, 2, 2, 0],
[0, 3, 2, 3],
[3, 2, 2, 3]])
In [49]: arr[idx]
Out[49]:
array([[9, 8, 8, 6],
[6, 9, 8, 9],
[9, 8, 8, 9]])
如果您想要一种不那么神奇且更具启发性的方法,那么下面的方法会更有帮助。
# flatten the `idx` array; index into `arr`; then reshape to `idx's` shape.
In [50]: arr[idx.ravel()].reshape(idx.shape)
Out[50]:
array([[9, 8, 8, 6],
[6, 9, 8, 9],
[9, 8, 8, 9]])
推荐阅读
- php - 获取 S3::putObject(): 最近创建的存储桶的 [AccessDenied] 错误(旧存储桶工作正常)
- python - Pandas 按列分组并创建带有结果的字典
- apache-flink - 在本地模式下更改 Apache Flink 绑定地址
- c - 功率递归程序 - 效率
- optimization - 如何对具有绝对约束的最小二乘优化问题进行建模?
- angular - 如何初始化 Angular Material Datepicker 输入表单域?
- c++ - .cpp 文件中纯虚函数的正确返回值应该是多少?
- sql - 在 SQL 中按 DESC 和 ASC 排序
- python - 如何从python中的字典字典中获取列表列表?
- python - 如何在 python 中使用 twitter API 抓取包含特定链接的推文?