When selecting elements from a 1-D NumPy Array, is there a way to skip elements?


#1

Question

When selecting elements from a 1-D NumPy Array, is there a way to skip elements?

Answer

Yes, actually, selecting elements from a 1-D Array is similar to list or string slicing.

Just like when slicing a list or string, we can include a third value, which is the step value, or the number of indexes to increment for each item in the new list or substring.

Code

# By default, step is 1, and selects each item 
# in the range of indexes.
test = np.array([92, 94, 88, 91, 87])

print test[0:5] 
# [92, 94, 88, 91 87]

# With a step of 2, it will skip every other element.
print test[0:5:2] 
# [92, 88, 87]