Home » How to Remove Specific Elements from NumPy Array

How to Remove Specific Elements from NumPy Array

by Erma Khan

You can use the following methods to remove specific elements from a NumPy array:

Method 1: Remove Elements Equal to Specific Value

#remove elements whose value is equal to 12
new_array = np.delete(original_array, np.where(original_array == 12))

Method 2: Remove Elements Equal to Some Value in List

#remove elements whose value is equal to 2, 5, or 12
new_array = np.setdiff1d(original_array, [2, 5, 12])

Method 3: Remove Elements Based on Index Position

#remove elements in index positions 0 and 6
new_array = np.delete(original_array, [0, 6])

The following examples show how to use each method in practice.

Example 1: Remove Elements Equal to Specific Value

The following code shows how to remove all elements from a NumPy array whose value is equal to 12:

import numpy as np

#define original array of values
original_array = np.array([1, 2, 2, 4, 5, 7, 9, 12, 12])

#remove elements whose value is equal to 12
new_array = np.delete(original_array, np.where(original_array == 12))

#view new array
print(new_array)

[1 2 2 4 5 7 9]

Notice that both elements in the array that were equal to 12 have been removed.

Example 2: Remove Elements Equal to Some Value in List

The following code shows how to remove all elements from a NumPy array whose values is equal to 2, 5, or 12:

import numpy as np

#define original array of values
original_array = np.array([1, 2, 2, 4, 5, 7, 9, 12, 12])

#remove elements whose value is equal to 2, 5, or 12
new_array = np.setdiff1d(original_array, [2, 5, 12])

#view new array
print(new_array)

[1 4 7 9]

Notice that all elements whose value was 2, 5, or 12 have been removed.

Example 3: Remove Elements Based on Index Position

The following code shows how to remove the elements in index positions 0 and 6 from a NumPy array:

import numpy as np

#define original array of values
original_array = np.array([1, 2, 2, 4, 5, 7, 9, 12, 12])

#remove elements in index positions 0 and 6
new_array = np.delete(original_array, [0, 6])

#view new array
print(new_array)

[ 2  2  4  5  7 12 12]

Notice that the elements in index position 0 (with value of 1) and index position 6 (with value of 9) have both been removed from the NumPy array.

Additional Resources

The following tutorials explain how to perform other common operations in Python:

How to Fill NumPy Array with Values
How to Replace Elements in NumPy Array
How to Get Specific Row from NumPy Array

Related Posts