Combining slicing and broadcasted indexing for multi-dimensional numpy arrays

后端 未结 3 1565
别跟我提以往
别跟我提以往 2021-01-23 09:27

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         


        
3条回答
  •  春和景丽
    2021-01-23 10:17

    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)
    

提交回复
热议问题