I have a 3D numpy array with integer values, something defined as:
import numpy as np
x = np.random.randint(0, 100, (10, 10, 10))
Now what I want to do is find the last slice (or alternatively the first slice) along a given axes (say 1) where a particular value occurs. At the moment, I do something like:
first=None
last=None
val = 20
for i in range(len(x.shape[1]):
slice = x[:, i, :]
if len(slice[slice==val]) > 0:
if not first:
first = i
last = i
return first, last
This seems a bit unpythonic and I wonder if there is some numpy magic to do this?