In this tutorial, we will look at how to get every nth element of a Numpy array with the help of some examples.
How to extract every nth element of a Numpy array?
You can use slicing to get every nth element of a Numpy array. Slice the array from its start to end and use n as the step parameter.
The following is the syntax –
# slicing array to get every nth element. Slicing uses the syntax ar[start:stop:step] ar[::n]
If applied on a Numpy array, it will give a Numpy array containing every nth element from the original array.
You can similarly slice lists in Python to get every nth element.
Let’s now look at examples of using the above syntax to get every nth element in a Numpy array.
First, we will create a Numpy array that we will use throughout this tutorial.
import numpy as np # create numpy array ar = np.arange(1, 6) # display the array ar
array([1, 2, 3, 4, 5])
Here, we used the
numpy.arange() function to create a Numpy array of integers from 1 to 5.
Example 1 – Get every 2nd value in the array
Let’s use the above syntax to get every 2nd value in the array
ar created above.
Since we want to extract every 2nd value,
# get every nth element, n=2 ar[::2]
array([1, 3, 5])
We get a Numpy array of every 2nd element in the original array starting from the first element (the element at index 0). The below image illustrates this better.
Note that when extracting the elements, their individual value doesn’t matter. Here, we’re using slicing to get every nth element based on its respective position.
If you instead want every nth value starting from the nth element (having index n-1), slice the array starting from n-1 and use n as the step size.
# get every nth element starting from the nth element, n=2 n = 2 ar[n-1::n]
We get every 2nd element starting from the 2nd element in the array.
Example 2 – Get every 3rd value in the array
Let’s look at another example. This time we will extract every 3rd value in the array starting from index 0, so
# get every nth element, n=3 ar[::3]
We get an array of every 3rd value starting from the first element (index=0) of the original array.
In this tutorial, we looked at how we can use slicing to get every nth value from a Numpy array. Since, slicing is not exclusive to Numpy arrays, you can use this method on other iterables in Python such as lists, tuples, etc.
You might also be interested in –
- Numpy – Get the Sign of Each Element in Array
- Numpy – Get All Even Elements in Array
- Extract the First N Elements of Numpy Array
- Extract the Last N Elements of Numpy Array
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.