Indexing NumPy 2D array with another 2D array

后端 未结 6 1717
孤独总比滥情好
孤独总比滥情好 2021-01-05 15:16

I have something like

m = array([[1, 2],
            [4, 5],
            [7, 8],
            [6, 2]])

and

select = array([         


        
6条回答
  •  伪装坚强ぢ
    2021-01-05 15:34

    I prefer to use NP.where for indexing tasks of this sort (rather than NP.ix_)

    What is not mentioned in the OP is whether the result is selected by location (row/col in the source array) or by some condition (e.g., m >= 5). In any event, the code snippet below covers both scenarios.

    Three steps:

    1. create the condition array;

    2. generate an index array by calling NP.where, passing in this condition array; and

    3. apply this index array against the source array


    >>> import numpy as NP
    
    >>> cnd = (m==1) | (m==5) | (m==7) | (m==6)
    >>> cnd
      matrix([[ True, False],
              [False,  True],
              [ True, False],
              [ True, False]], dtype=bool)
    
    >>> # generate the index array/matrix 
    >>> # by calling NP.where, passing in the condition (cnd)
    >>> ndx = NP.where(cnd)
    >>> ndx
      (matrix([[0, 1, 2, 3]]), matrix([[0, 1, 0, 0]]))
    
    >>> # now apply it against the source array   
    >>> m[ndx]
      matrix([[1, 5, 7, 6]])
    


    The argument passed to NP.where, cnd, is a boolean array, which in this case, is the result from a single expression comprised of compound conditional expressions (first line above)

    If constructing such a value filter doesn't apply to your particular use case, that's fine, you just need to generate the actual boolean matrix (the value of cnd) some other way (or create it directly).

提交回复
热议问题