简体   繁体   中英

How do you get the indices of a Numpy slice with a step?

Original Question (with stupid example): eg 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. eg

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])

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])

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),)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM