How to skip every Nth index of NumPy array ?
In this article, we will see how to skip every Nth index of the NumPy array. There are various ways to access and skip elements of a NumPy array :
Method 1: Naive Approach
A counter can be maintained to keep a count of the elements traversed so far, and then as soon as the Nth position is encountered, the element is skipped and the counter is reset to 0. All the elements are appended to a new list excluding the Nth index element encountered while traversal. The time required during this is equivalent to O(n), where n is the size of the numpy array. In case the elements need to be just printed and not stored, we can skip the declaration of creation of another array.
Array after skipping nth element
[3.0, 6.7, 8.7, 1.3, 4.5, 6.5, 3.0, 6.7, 8.7, 1.3, 4.5, 6.5]
Method 2: Using NumPy modulus method
The array can first be arranged into chunks of evenly spaced intervals, using the numpy.arange() method.
- start: Start of the interval
- stop: End of the interval
- step: Steps between the start and end interval
Then, the np.mod() method is applied over the list’s intervals obtained and each element’s modulo is then computed with the nth index. The elements of the original array whose modulo output is not 0, are returned as the final list.
[0 1 2 3 2 5 2 7 2 9]
Array after skipping elements :
[1 2 2 5 7 2]
Method 3: NumPy Slicing
NumPy slicing is basically data subsampling where we create a view of the original data, which incurs constant time. The changes are made to the original array and the entire original array is kept in memory. A copy of the data can also be made explicitly.
Here, where the start is the starting index, the end is the stopping index, and st is the step, where the step is not equivalent to 0. And, it returns a sub-array that contains the elements belonging to the st index respectively. The indexes of the array are assumed to be starting at 0.
List after n=3rd element access
[0 3 2 9]