How to Skip every Nth index of Numpy array?

In NumPy arrays, you can skip every Nth index using several approaches: modulus operations with np.mod(), array slicing, or loop-based filtering. These techniques are useful for data sampling, filtering, and array manipulation tasks.

Understanding the Modulus Approach

The modulus approach uses np.mod() to identify which indices to skip. It works by calculating the remainder when dividing each index by N, then filtering elements where the remainder is not zero.

import numpy as np

# Create a sample array
x = np.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140])

# Skip every 5th element (indices 0, 5, 10, etc.)
new_arr = x[np.mod(np.arange(x.size), 5) != 0]

print("Original array:")
print(x)
print("\nAfter skipping every 5th element:")
print(new_arr)
Original array:
[ 10  20  30  40  50  60  70  80  90 100 110 120 130 140]

After skipping every 5th element:
[ 20  30  40  50  70  80  90 100 120 130 140]

Using Array Slicing

NumPy slicing provides a simpler way to access every Nth element directly using the step parameter in slice notation [start:stop:step].

import numpy as np

x = np.array([9, 11, 12, 33, 32, 55, 88, 97, 23, 19, 86, 11, 3])

# Take every 4th element starting from index 0
result = x[::4]

print("Original array:")
print(x)
print("\nEvery 4th element:")
print(result)
Original array:
[ 9 11 12 33 32 55 88 97 23 19 86 11  3]

Every 4th element:
[ 9 32 23  3]

Loop-Based Filtering

For more complex filtering logic, you can use loops with conditional statements to skip elements at specific positions.

import numpy as np

numbers = np.array([124, 301, 627, 387, 812, 113, 145, 65])
n = 2  # Skip every 2nd element (even indices)

# Filter elements not at even positions
filtered_array = []
for i, value in enumerate(numbers):
    if i % n != 0:
        filtered_array.append(value)

print("Original array:")
print(numbers)
print(f"\nAfter skipping every {n}nd element:")
print(filtered_array)
Original array:
[124 301 627 387 812 113 145  65]

After skipping every 2nd element:
[301, 387, 113, 65]

Comparison of Methods

Method Best For Performance Readability
Modulus with np.mod() Complex filtering conditions Fast Medium
Array slicing [::n] Simple regular intervals Very fast High
Loop-based filtering Custom logic Slower High

Conclusion

Use array slicing [::n] for simple regular sampling. Use np.mod() for more complex filtering patterns. Loop-based approaches offer maximum flexibility but are slower for large arrays.

Updated on: 2026-03-27T08:04:11+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements