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

后端 未结 7 1544
闹比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:17

    I don't think that x[[1,3]][:,[1,3]] is hardly readable. If you want to be more clear on your intent, you can do:

    a[[1,3],:][:,[1,3]]
    

    I am not an expert in slicing but typically, if you try to slice into an array and the values are continuous, you get back a view where the stride value is changed.

    e.g. In your inputs 33 and 34, although you get a 2x2 array, the stride is 4. Thus, when you index the next row, the pointer moves to the correct position in memory.

    Clearly, this mechanism doesn't carry well into the case of an array of indices. Hence, numpy will have to make the copy. After all, many other matrix math function relies on size, stride and continuous memory allocation.

提交回复
热议问题