As one of the approaches, we can get nonzero indices and get the average of them as the center of mass, for example:
np.flatnonzero(x).mean()
, , :
np.flatnonzero(x[:-1] != x[1:]).mean()+0.5
-
In [72]: x = np.zeros(10000,dtype=int)
In [73]: x[100:2000] = 1
In [74]: %timeit np.flatnonzero(x).mean()
10000 loops, best of 3: 115 µs per loop
In [75]: %timeit np.flatnonzero(x[:-1] != x[1:]).mean()+0.5
10000 loops, best of 3: 38.7 µs per loop
, np.nonzero()[0] np.flatnonzero np.sum np.mean -
In [107]: %timeit (np.nonzero(x[:-1] != x[1:])[0].sum()+1)/2.0
10000 loops, best of 3: 30.6 µs per loop
, , , , np.mean, ,
start,stop = np.flatnonzero(x[:-1] != x[1:])
out = (stop + start + 1)/2.0
-
In [90]: %timeit start,stop = np.flatnonzero(x[:-1] != x[1:])
10000 loops, best of 3: 21.3 µs per loop
In [91]: %timeit (stop + start + 1)/2.0
100000 loops, best of 3: 4.45 µs per loop
, np.nonzero()[0] .