Python numpy 数组索引。这是如何工作的?
Python numpy array indexing. How is this working?
我遇到了这个 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 数组的最后一个维度上工作,但我完全不清楚重新排列和重塑是如何完成的,但这确实 returns 一个形状数组 (10, 10, 3, 3) .我很惊讶也很困惑!
来自高级索引文档 - bi rico 的 link。
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 代码(有效),对我来说它看起来很神奇。但是,我无法弄清楚这段代码在做什么。为了复制它,我写了一段测试代码:
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 数组的最后一个维度上工作,但我完全不清楚重新排列和重塑是如何完成的,但这确实 returns 一个形状数组 (10, 10, 3, 3) .我很惊讶也很困惑!
来自高级索引文档 - bi rico 的 link。
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).