As far as I can see it, it isn’t covered in the indexing, slicing and iterating scipy tutorial, so let me ask it here:
Say I’ve
JavaScript
x
7
1
x = np.array([[1,2],[3,4],[5,6],[7,8],[9,0]])
2
x: array([[1, 2],
3
[3, 4],
4
[5, 6],
5
[7, 8],
6
[9, 0]])
7
How do I slice the array in order get both the first and last rows:
JavaScript
1
5
1
y: array([[1, 2],
2
[3, 4],
3
[7, 8],
4
[9, 0]])
5
Advertisement
Answer
I don’t know if there’s a slick way to do that. You could list the indices explicitly, of course:
JavaScript
1
6
1
>>> x[[0,1,-2,-1]]
2
array([[1, 2],
3
[3, 4],
4
[7, 8],
5
[9, 0]])
6
Or use r_
to help, which would probably be more convenient if we wanted more rows from the head or tail:
JavaScript
1
6
1
>>> x[np.r_[0:2, -2:0]]
2
array([[1, 2],
3
[3, 4],
4
[7, 8],
5
[9, 0]])
6