且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

结合切片和广播的索引多维numpy的阵列

更新时间:2023-01-22 20:12:20

在受限制的索引情况下,像这样使用九_ ,这是可以做到的索引在连续的步骤。

  A [IND1]

是相同的

  A [I1] [:, 12] [:,:,I3]

和自 I2 是品种齐全,

  A [I1] [...,I3]

如果你只有 IND2 可用

  A [IND2 [0] .flatten()] [IND2 [2] .flatten()]

在更广泛的背景下,你必须知道如何 J0,J1,J2 与对方,但播出时,它们是由生成IX _ ,关系很简单。

我可以想象它会是方便的分配情况 A1 = A [I1] ,其次是各种涉及行动 A1 ,包括但不限于 A1 [...,I3] 。你要知道,当 A1 是一个观点,当它是一个副本。

另一个索引工具是

  A.take(I0,轴= 0)。取(I2,轴= 2)

I have a ND numpy array (let say for instance 3x3x3) from wich I'd like to extract a sub-array, combining slices and index arrays. For instance:

import numpy as np  
A = np.arange(3*3*3).reshape((3,3,3))
i0, i1, i2 = ([0,1], [0,1,2], [0,2])
ind1 = j0, j1, j2 = np.ix_(i0, i1, i2)
ind2 = (j0, slice(None), j2)
B1 = A[ind1]
B2 = A[ind2]

I would expect that B1 == B2, but actually, the shapes are different

>>> B1.shape
(2, 3, 2)
>>> B2.shape
(2, 1, 2, 3)
>>> B1
array([[[ 0,  2],
        [ 3,  5],
        [ 6,  8]],

       [[ 9, 11],
        [12, 14],
        [15, 17]]])
>>> B2
array([[[[ 0,  3,  6],
         [ 2,  5,  8]]],

       [[[ 9, 12, 15],
         [11, 14, 17]]]])

Someone understands why? Any idea of how I could get 'B1' by manipulating only 'A' and 'ind2' objects? The goal is that it would work for any nD arrays, and that I would not have to look for the shape of dimensions I want to keep entirely (hope I'm clear enough:)). Thanks!!
---EDIT---
To be clearer, I would like to have a function 'fun' such that

A[fun(ind2)] == B1

In restricted indexing cases like this using ix_, it is possible to do the indexing in successive steps.

A[ind1]

is the same as

A[i1][:,i2][:,:,i3]

and since i2 is the full range,

A[i1][...,i3]

If you only have ind2 available

A[ind2[0].flatten()][[ind2[2].flatten()]

In more general contexts you have to know how j0,j1,j2 broadcast with each other, but when they are generated by ix_, the relationship is simple.

I can imagine circumstances in which it would be convenient to assign A1 = A[i1], followed by a variety of actions involving A1, including, but not limited to A1[...,i3]. You have to be aware of when A1 is a view, and when it is a copy.

Another indexing tool is take:

A.take(i0,axis=0).take(i2,axis=2)