Numpy tutorial - Boolean indexing

前端 未结 1 1310
悲&欢浪女
悲&欢浪女 2020-12-21 05:55

Reading Numpy quick tutorial, I cannot understand this sentence.

a = np.arange(12).reshape(3,4)
b1 = np.array([False,True,True]) 
b2 = np.array([True,False,T         


        
相关标签:
1条回答
  • 2020-12-21 06:29

    It's because you are performing integer array indexing there.

    Internally, the indices are computed from the boolean arrays -

    In [72]: idx1 = np.flatnonzero(b1)
    
    In [73]: idx2 = np.flatnonzero(b2)
    
    In [75]: idx1
    Out[75]: array([1, 2])
    
    In [76]: idx2
    Out[76]: array([0, 2])
    

    Then, the integer array indexing is performed on each group of indices using each element from the indexing arrays -

    In [77]: a[1,0] # 1 from idx1[0], 0 from idx2[0]
    Out[77]: 4
    
    In [78]: a[2,2] # 2 from idx1[1], 2 from idx2[1]
    Out[78]: 10
    

    To achieve that MATLAB styled block extraction, we need to use open arrays and index into each of those axes/dims. To create such open arrays in NumPy, we have np.ix_ -

    In [89]: np.ix_(b1,b2)
    Out[89]: 
    (array([[1],
            [2]]), array([[0, 2]]))
    
    In [90]: a[np.ix_(b1,b2)]
    Out[90]: 
    array([[ 4,  6],
           [ 8, 10]])
    
    0 讨论(0)
提交回复
热议问题