How do I slice a numpy array to get both the first and last two rows
Question:
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
x = np.array([[1,2],[3,4],[5,6],[7,8],[9,0]])
x: array([[1, 2],
[3, 4],
[5, 6],
[7, 8],
[9, 0]])
How do I slice the array in order get both the first and last rows:
y: array([[1, 2],
[3, 4],
[7, 8],
[9, 0]])
Answers:
I don’t know if there’s a slick way to do that. You could list the indices explicitly, of course:
>>> x[[0,1,-2,-1]]
array([[1, 2],
[3, 4],
[7, 8],
[9, 0]])
Or use r_
to help, which would probably be more convenient if we wanted more rows from the head or tail:
>>> x[np.r_[0:2, -2:0]]
array([[1, 2],
[3, 4],
[7, 8],
[9, 0]])
Alternatively,you can use indices to remove as
mask = np.ones(len(x), dtype=np.bool)
mask[2:3] = False # that you want to remove
y = x[mask]
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
x = np.array([[1,2],[3,4],[5,6],[7,8],[9,0]])
x: array([[1, 2],
[3, 4],
[5, 6],
[7, 8],
[9, 0]])
How do I slice the array in order get both the first and last rows:
y: array([[1, 2],
[3, 4],
[7, 8],
[9, 0]])
I don’t know if there’s a slick way to do that. You could list the indices explicitly, of course:
>>> x[[0,1,-2,-1]]
array([[1, 2],
[3, 4],
[7, 8],
[9, 0]])
Or use r_
to help, which would probably be more convenient if we wanted more rows from the head or tail:
>>> x[np.r_[0:2, -2:0]]
array([[1, 2],
[3, 4],
[7, 8],
[9, 0]])
Alternatively,you can use indices to remove as
mask = np.ones(len(x), dtype=np.bool)
mask[2:3] = False # that you want to remove
y = x[mask]