This tutorial will discuss about unique ways to remove every nth element from a numpy array.
Suppose we have a numpy array of numbers, like this,
numbers = np.array([34, 35, 78, 61, 56, 35, 90, 35])
We want to delete every 2nd element from this array.
For this we will create a boolean array or a mask, where every Nth element will be marked as False like this,
# Create a mask where each Nth element # is marked as False mask = np.arange(len(numbers)) % n != 0 mask = ~mask
It will return a boolean array where every Nth element is False. Then we can pass this modified boolean sequence into the subscript operator of number array like this,
# Remove every Nth element from the array numbers = numbers[mask]
It will return a copy of number array after removing every Nth element from the original array.
In the below example we are going to remove every second element from the number array.
- Remove Elements from a NumPy Array in a specific order
- Remove duplicates from NumPy Array in Python
- Remove elements from Array Less than a value in Python
- Remove Last element from a NumPy Array in Python
Let’s see the complete example,
import numpy as np # create sample numpy array numbers = np.array([34, 35, 78, 61, 56, 35, 90, 35]) print('Before removing elements:') print(numbers) # Nth value n = 2 # Create a mask where each Nth element # is marked as True mask = np.arange(len(numbers)) % n != 0 mask = ~mask # Remove every Nth element from the array numbers = numbers[mask] print('After removing elements:') print(numbers)
Before removing elements: [34 35 78 61 56 35 90 35] After removing elements: [34 78 56 90]
We learned how to delete every Nth element from a NumPy Array in Python.