Python numpy 数组索引。这是如何工作的?

标签 python numpy matrix-indexing

我遇到了这个 python 代码(有效),对我来说它看起来很神奇。但是,我无法弄清楚这段代码在做什么。为了复制它,我编写了一段测试代码:

import numpy as np

# Create a random array which represent the 6 unique coeff. 
# of a symmetric 3x3 matrix
x = np.random.rand(10, 10, 6)

所以,我有 100 个对称的 3x3 矩阵,我只存储唯一的组件。现在,我想生成完整的 3x3 矩阵,这就是神奇的地方。

indices = np.array([[0, 1, 3],
                    [1, 2, 4],
                    [3, 4, 5]])

我明白这是在做什么。这就是0-5索引分量在3x3矩阵中的排列方式,以具有对称矩阵。

mat = x[..., indices]

这条线让我迷路了。因此,它正在处理 x 数组的最后一个维度,但我完全不清楚重新排列和 reshape 是如何完成的,但这确实返回了一个形状数组 (10, 10, 3, 3)。我很惊讶也很困惑!

最佳答案

来自高级索引文档 - bi rico 的链接。

Example

Suppose x.shape is (10,20,30) and ind is a (2,3,4)-shaped indexing intp array, thenresult = x[...,ind,:] has shape (10,2,3,4,30) because the (20,)-shaped subspace has been replaced with a (2,3,4)-shaped broadcasted indexing subspace. If we let i, j, kloop over the (2,3,4)-shaped subspace then result[...,i,j,k,:] =x[...,ind[i,j,k],:]. This example produces the same result as x.take(ind, axis=-2).

关于Python numpy 数组索引。这是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27851051/

相关文章:

python - 操作直方图 bins Python

python - 使用索引迭代两个 2D numpy 数组

python - 如何从numpy中的一维数组中提取零维切片

matlab - 带单元格的 Subsref

python - 没有 float64 转换的两个具有缺失值的 uint64 系列的最小值

python - 有没有办法从图形图像中提取数据并将其存储在 Excel 工作表或 csv 文件中?

python - 使用 Python 从 XML 解析矩阵

python - 使用 Coffin 设置 Dajaxice 时出现未知标签 'dajaxice_js_import'

python - 在 csv 文件中添加填充以使数据框可供 pandas 读取

matlab - 在 Matlab 中使用指标矩阵创建标签向量