简体   繁体   中英

Understanding the slicing of NumPy array

I haven't understood the output of the following program:

import numpy as np

myList = [[1,   2,  3,  4],
          [5,   6,  7,  8],
          [9,  10, 11, 12],
          [13, 14, 15, 16]]

myNumpyArray = np.array(myList)

print(myNumpyArray[0:3, 1:3])

Output

[[ 2  3]
 [ 6  7]
 [10 11]]

What I knew that would be the intersection of all rows, and 2nd to 4th columns. In that logic, the output should be:

 2   3  4
 6   7  8
10  11 12
14  15 16

What am I missing here?

The ending indices (the 3's in 0:3 and 1:3 ) are exclusive, not inclusive, while the starting indices ( 0 and 1 ) are in fact inclusive. If the ending indices were inclusive, then the output would be as you expect. But because they're exclusive, you're actually only grabbing rows 0, 1, and 2, and columns 1 and 2. The output is the intersection of those, which is equivalent to the output you're seeing.

If you are trying to get the data you expect, you can do myNumpyArray[:, 1:] . The : simply grabs all the elements of the array (in your case, in the first dimension of the array), and the 1: grabs all the content of the array starting at index 1, ignoring the data in the 0th place.

This is a classic case of just needing to understand slice notation.

inside the brackets, you have the slice for each dimension:

arr[dim1_start:dim1_end, dim2_start, dim2_end]

For the above notation, the slice will include the elements starting at dimX_start , up to, and not including, dimX_end .

So, for what you wrote: myNumpyArray[0:3, 1:3]

you selected rows 0, 1, and 2 (not including 3) and columns 1 and 2 (not including 3)


I hope that helps explain your results.


For the result you were expecting, you would need something more like:

print(myNumpyArray[0:4, 1:4])

For more info on slicing, you might go to the numpy docs or look at a similar question posted a while back.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM