I have a python script that is reading slices from a 3D array, like this:
def get_from_array(axis, start, end, array):
if axis == 0:
slice = array[start:end, :, :]
elif axis == 1:
slice = array[:, start:end, :]
elif axis == 2:
slice = array[:, :, start:end]
return slice
I can't help but think there must be a better way of doing this! Any suggestions?
S
You can do something like this:
idx = [slice(None)] * array.ndim
idx[axis] = slice(start, end)
myslice = array[tuple(idx)]
You can also use np.take
. Then you can do it in one line more naturally.
a.take(np.arange(start,end), axis=axis)
Notes:
:
slice notation but replace that with range
For example:
In [135]: a = np.arange(3*3*3).reshape(3,3,3)
In [136]: a.take(np.arange(1,2), axis=1)
Out[136]:
array([[[ 3, 4, 5]],
[[12, 13, 14]],
[[21, 22, 23]]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With