I am trying to slice the below array to get rows 2 and 3 and the first column in addition to the columns between the 2nd and last columns, but every slice I have tried does not seem to work. For example, the first print statement below gives a syntax error because of the : in the brackets. I have also tried to simply concatenate the arrays, but I don’t think this is the most efficient way to accomplish this problem.
import numpy as np
y = np.arange(35).reshape(5, 7)
# My ultimate goal is to do a slice similar to this expression, but this of course gives
# an error.
print y[[1, 2], [0, 2:-1]]
# This works, but I feel it is inefficient, although I could be wrong.
print np.hstack((y[[1, 2], 0][:, np.newaxis], y[[1, 2], 2:-1]))
Any suggestions would be greatly appreciated.
I don’t know if this is what you’re asking for but try
Numpy can be sliced similar to standard Python lists but the dimensions add some trickiness but I still find this solution to be really elegant compared to nesting or looping reshapes but sometimes this will not always be the end-all-be-all solution.
Edit:
It doesn’t look good but it’s better than a reshape or huge matrix changes
This is the same as saying
y[1:3, [0, 2:-1]]without having to reshape the array or iterate through excess elements, you specify the indexes you care about by making a list of[0] +the remaining columns in that dimension.