Slicing of a NumPy 2d array, or how do I extract an mxm submatrix from an nxn array (n>m)?

后端 未结 7 1551
闹比i
闹比i 2020-11-27 09:30

I want to slice a NumPy nxn array. I want to extract an arbitrary selection of m rows and columns of that array (i.e. without any pattern in the numbers of rows/col

7条回答
  •  暖寄归人
    2020-11-27 10:18

    If you want to skip every other row and every other column, then you can do it with basic slicing:

    In [49]: x=np.arange(16).reshape((4,4))
    In [50]: x[1:4:2,1:4:2]
    Out[50]: 
    array([[ 5,  7],
           [13, 15]])
    

    This returns a view, not a copy of your array.

    In [51]: y=x[1:4:2,1:4:2]
    
    In [52]: y[0,0]=100
    
    In [53]: x   # <---- Notice x[1,1] has changed
    Out[53]: 
    array([[  0,   1,   2,   3],
           [  4, 100,   6,   7],
           [  8,   9,  10,  11],
           [ 12,  13,  14,  15]])
    

    while z=x[(1,3),:][:,(1,3)] uses advanced indexing and thus returns a copy:

    In [58]: x=np.arange(16).reshape((4,4))
    In [59]: z=x[(1,3),:][:,(1,3)]
    
    In [60]: z
    Out[60]: 
    array([[ 5,  7],
           [13, 15]])
    
    In [61]: z[0,0]=0
    

    Note that x is unchanged:

    In [62]: x
    Out[62]: 
    array([[ 0,  1,  2,  3],
           [ 4,  5,  6,  7],
           [ 8,  9, 10, 11],
           [12, 13, 14, 15]])
    

    If you wish to select arbitrary rows and columns, then you can't use basic slicing. You'll have to use advanced indexing, using something like x[rows,:][:,columns], where rows and columns are sequences. This of course is going to give you a copy, not a view, of your original array. This is as one should expect, since a numpy array uses contiguous memory (with constant strides), and there would be no way to generate a view with arbitrary rows and columns (since that would require non-constant strides).

提交回复
热议问题