[英]How to index/slice 3D numpy array
I'm relatively new to python/numpy.我对 python/numpy 比较陌生。 I have a 3D numpy array of TxNxN.
我有一个 TxNxN 的 3D numpy 数组。 It contains a sequence of symmetrical NxN matrices.
它包含一系列对称的 NxN 矩阵。 I want convert it to a 2D array of TxM (where M = N(N+1)/2).
我想将其转换为 TxM 的二维数组(其中 M = N(N+1)/2)。 How can I do that?
我怎样才能做到这一点? I can certainly use 3 loops, but I thought there probably better ways to do that in python/numpy.
我当然可以使用 3 个循环,但我认为在 python/numpy 中可能有更好的方法来做到这一点。
It seems that you want to get the upper triangle or lower triangle of each symmetric matrix.似乎您想获得每个对称矩阵的上三角形或下三角形。 A simple method is to generate a mask array and apply it to each 2D array:
一个简单的方法是生成一个掩码数组并将其应用于每个二维数组:
>>> e
array([[[0, 1, 2, 3],
[1, 2, 3, 0],
[2, 3, 0, 1],
[3, 0, 1, 2]],
[[1, 2, 3, 4],
[2, 3, 4, 1],
[3, 4, 1, 2],
[4, 1, 2, 3]],
[[2, 3, 4, 5],
[3, 4, 5, 2],
[4, 5, 2, 3],
[5, 2, 3, 4]]])
>>> ii, jj = np.indices(e.shape[1:])
>>> jj >= ii
array([[ True, True, True, True],
[False, True, True, True],
[False, False, True, True],
[False, False, False, True]])
>>> e[:, jj >= ii]
array([[0, 1, 2, 3, 2, 3, 0, 0, 1, 2],
[1, 2, 3, 4, 3, 4, 1, 1, 2, 3],
[2, 3, 4, 5, 4, 5, 2, 2, 3, 4]])
Using the numpy.triu_indices
function can do better, but you can't put the obtained indices tuple directly between square brackets.使用
numpy.triu_indices
函数可以做得更好,但不能将获得的索引元组直接放在方括号之间。 You need to unpack them first:您需要先解压缩它们:
>>> i, j = np.triu_indices(e.shape[1])
>>> e[:, i, j]
array([[0, 1, 2, 3, 2, 3, 0, 0, 1, 2],
[1, 2, 3, 4, 3, 4, 1, 1, 2, 3],
[2, 3, 4, 5, 4, 5, 2, 2, 3, 4]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.