So I have an array, and I'm trying to get a sub-array from it.
x = np.arange(0,100).reshape((10, 10))
array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
[20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
[30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
[40, 41, 42, 43, 44, 45, 46, 47, 48, 49],
[50, 51, 52, 53, 54, 55, 56, 57, 58, 59],
[60, 61, 62, 63, 64, 65, 66, 67, 68, 69],
[70, 71, 72, 73, 74, 75, 76, 77, 78, 79],
[80, 81, 82, 83, 84, 85, 86, 87, 88, 89],
[90, 91, 92, 93, 94, 95, 96, 97, 98, 99]])
So, to get the first two rows and two columns, I use the following. But when I try to get rows {5,6,7} and columns {3,4,5}, it is not giving me what I want.
x[:2,:2]
x[5:7,3:5]
This is what I need, out of the initial array.
But I do not understand how to get it.
Slices are half-open intervals. You need to increase each upper bound by one.
>>> x[5:8,3:6]
array([[53, 54, 55],
[63, 64, 65],
[73, 74, 75]])
Also, the indices start at 0, which is why x[:2,:2]
worked the way you expected, despite your expectation being off. :2
is short for 0:2
, not 1:2
.