Python numpy数组索引。这是怎么回事?

2024-04-20 06:36:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我偶然发现了这段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数组的最后一个维度上工作的,但是我一点也不清楚如何重新排列和重塑,但是这确实返回了一个形状数组(10,10,3,3)。我感到惊讶和困惑!你知道吗


Tags: 代码importnumpywhichascreatenp组件
1条回答
网友
1楼 · 发布于 2024-04-20 06:36:54

来自高级索引文档-birico的链接。你知道吗

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).

相关问题 更多 >