Reputation: 5011
Original Question (with stupid example): e.g my question is simple, how do you get the index positions of a slice with step, in Numpy. See example below where you can use np.nonzero on a slice but include a step and you don't. Is there another option
import numpy as np
d = np.hstack([np.arange(6), np.arange(6), np.arange(6)])
step = 6
np.nonzero(d[0:-1])
Out[45]: (array([ 1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 13, 14, 15, 16]),)
In [46]: np.nonzero(d[0:-1:step])
Out[46]: (array([], dtype=int64),)
`
Question I should have asked.
How do you get the indices of a slice with a step in Numpy. e.g
import numpy as np
d = np.hstack([np.arange(6), np.arange(6), np.arange(6)])
step = 6
#The indices of d[0:-1:step] would be:
array([ 0, 6, 12])
Upvotes: 2
Views: 6078
Reputation: 394169
np.nonzero
works with a step arg, it's just your step arg matches the indices where there are no non-zero values:
In[59]:
d[0:-1:step]
Out[59]: array([0, 0, 0])
For instance if your step arg was 5
then it works as expected:
In[60]:
d[0:-1:5]
Out[60]: array([0, 5, 4, 3])
In[61]:
np.nonzero(d[0:-1:5])
Out[61]: (array([1, 2, 3], dtype=int64),)
Update
If you just want the indices from a slice then you can just apply the slice to a range:
In[72]:
np.arange(len(d))[0:-1:step]
Out[72]: array([ 0, 6, 12])
Or just do arange
and pass the length and step params:
In[73]:
np.arange(0, len(d), step)
Out[73]: array([ 0, 6, 12])
Update 2
Thanks to @Divakar (the numpy master) you can use r_
to convert slice notation to an array, plus this is less typing:
In[79]:
np.r_[:len(d):step]
Out[79]: array([ 0, 6, 12])
Upvotes: 5
Reputation: 1709
if your step=6
your numpy array d
will act like
step = 6
print((d[0:-1:step]))
output:[0 0 0]
because
d = np.hstack([np.arange(6), np.arange(6), np.arange(6)])
print(d)
output: [0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5]
so step=6
np.nonzero(d[0:-1:step])
output: (array([], dtype=int64),)
Upvotes: 0