加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-20 13:47:06 所属栏目:Python 来源:网络整理
导读:我遇到了这个 python代码(有效),对我来说这看起来很神奇.但是,我无法弄清楚这段代码在做什么.为了复制它,我写了一个测试代码: import numpy as np# Create a random array which represent the 6 unique coeff. # of a symmetric 3x3 matrixx = np.random.r
我遇到了这个 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个对称3×3矩阵,我只存储独特的组件.现在,我想生成完整的3×3矩阵,这就是魔术发生的地方.

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

我明白这是做什么的.这就是0-5指数分量应该如何排列在3×3矩阵中以具有对称矩阵.

mat = x[...,indices]

这条线让我输了.因此,它正在处理x数组的最后一个维度,但我并不清楚如何重新排列和重新整形,但这确实会返回一个形状数组(10,3,3).我感到惊讶和困惑!

解决方法

从高级索引文档 – bi rico的链接.

Example

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读