How to Remove Specific Elements in a Numpy Array

Summary: The most straightforward way to remove an element at a given index from a NumPy array is to call the function np.delete(array, index) that returns a new array with the element removed.


Problem: Given a Numpy Array; how to remove specific elements from the Numpy array?

Example: Consider the following Numpy array as shown below:

import numpy as np

arr = np.array([10, 20, 30, 40, 50])

Challenge: How will you remove the elements 20 and 40 from the above array?

Expected Output:

[10 30 50]

Video Walkthrough

Method 1: Using numpy.delete()

Prerequisite:

numpy.delete() is a method of the Numpy library that deletes elements from a numpy array based on a given index/position.
Syntax: numpy.delete(arr, obj, axis=None)
Here:

  • arr represents the numpy array from which the elements have to be removed.
  • obj represents the index/position or a list of indices of the elements that have to be deleted from the numpy array.
  • axis represents the axis along which you want to delete the elements,i.e.,
    • axis = 1 indicates deletion of elements across the column.
    • axis = 0 indicates deletion of elements across the rows.
    • If axis = None, then flatten the given array before applying delete on it.

It returns a copy of the passed numpy array after deleting the elements at the specified index/indices.

β¦ΏDelete Array Elements Using Their Index

Approach: Use the numpy.array(arr,obj) function such that obj represents a list of indices from which the elements have to be removed.

Code:

import numpy as np

arr = np.array([10, 20, 30, 40, 50])
delete_indices = [1, 3]
new_arr = np.delete(arr, delete_indices)
print(new_arr)

Output:

[10 30 50]

β¦ΏDelete Array Elements Directly

np.where() is a function of the Numpy library which allows you to select certain elements from a given Numpy array based on a specific condition.

Approach:

Call the numpy.where(condition) function to create a boolean mask. You can provide multiple conditions with the help of operators like &(and), |(or). In our example the condition to select the two elements to be removed will be: np.where((arr == 20) | (arr == 40)).

Once the elements have been selected, call the numpy.delete(arr, obj) method such that obj represents the elements at the indices based on the specified condition.

import numpy as np

arr = np.array([10, 20, 30, 40, 50])
new_arr = np.delete(arr, np.where((arr == 20) | (arr == 40)))
print(new_arr)

Ouput:

[10 30 50]

Method 2: Using numpy.setdiff1d

Prerequisite:

numpy.setdiff1d(arr1, arr2, assume_unique=False) is a function of the Numpy library that finds the difference between two arrays and returns the unique values in the two arrays.

  • arr1 and arr2 represent the input arrays.
  • assume_unique : bool
    • When this parameter is True, then both the input arrays are considered to be unique, which fastens the calculation speed. By default it is False.

Approach:

  • Create a Numpy array that stores the elements that have to be removed from the given array.
  • Call np.setdiff1d(arr, arr_) such that arr represents the given array while arr_ represents the array storing the elements to be removed. This will return an array containing the elements that are not present in both the arrays. In other words the elements to be deleted will be removed from the original array.

Code:

import numpy as np

arr = np.array([10, 20, 30, 40, 50])
arr_ = np.array([20, 40])
new_arr = np.setdiff1d(arr, arr_)
print(new_arr)

Output:

[10 30 50]

Caution: The setdiff1d will generate a sorted output.

Method 3: Using ~np.isin

Prerequisite:

The numpy.isin(target_array, list) method returns a boolean array by comparing one array with another array which have different elements with different sizes.

Example:

import numpy as np

arr_1 = np.array([10, 20, 30, 40, 50])
arr_2 = np.array([10, 30, 50])
res = np.isin(arr_1, arr_2)
print(res)

# OUTPUT: [ True False  True False  True]

β¦ΏDelete by Elements

Approach:

  • Create an array that contains the elements to be removed.
  • Call the ~np.isin(arr, arr_) upon the given array and the array that contains the elements to be removed. This negates and creates a boolean mask by checking the values in the two arrays passed.
  • Return the resultant array by passing the boolean mask generated above as arr[~np.isin(arr, arr_)]. Here, arr represents the given array and the boolean mask helps us to gather the elements for the True values.

Code:

import numpy as np

arr = np.array([10, 20, 30, 40, 50])
arr_ = np.array([20, 40])
new_arr = arr[~np.isin(arr, arr_)]
print(new_arr)

# OUTPUT --> [10 30 50]

β¦ΏDelete by Indices

Let’s have a look at the code before we dive into the explanation:

import numpy as np

arr = np.array([10, 20, 30, 40, 50])
indices_to_remove = [1, 3]
new_arr = arr[~np.isin(np.arange(arr.size), indices_to_remove)]
print(new_arr)

# OUTPUT --> [10 30 50]

Explanation: To understand the working principle behind the above approach let us have a look at the step by step breakdown of the program:

  • arr ➜ [10, 20, 30, 40, 50]
  • indices_to_remove ➜ [1, 3]

Now let’s dive deep into the working principle behind the following line of code: arr[~np.isin(np.arange(arr.size), indices_to_remove)]. To understand this, let us break it down and find out the output returned by each function used in this line of code.

  • arr.size returns 5
  • np.arange(arr.size) returns [0,1,2,3,4]
  • Thus, we have a fnction which looks something like this: arr[~np.isin([0,1,2,3,4], [1,3])]
  • This further evaluates to: arr[~([ False True False True False])]
  • After negation: arr[True False True False True]
  • Finally the values at the indices marked as True will be returned, i.e., values at indices 0,1,3. Thus the output is [10 30 50].

Method 4: Using ~np.in1d

Approach: If you don’t know the indices from which you want to remove the elements, you can utilize the in1d function of the Numpy library.

The np.in1d() function compares two 1D arrays and returns True if the element in one array is also present in the other array. To delete the elements, you simply have to negate the values that are returned by this function.

Code:

import numpy as np

arr = np.array([10, 20, 30, 40, 50])
arr_ = np.array([20, 40])
new_arr = arr[~np.in1d(arr, arr_)]
print(new_arr)

# OUTPUT --> [10 30 50]

Method 5: Using a List Comprehension

Another workaround to solve this problem is to use a list comprehension as shown below. Though this might not be the most pythonic solution to our problem but it solves the purpose. Hence, we included this solution in this tutorial.

Code:

import numpy as np

arr = np.array([10, 20, 30, 40, 50])
indices = np.array([1, 3])  # feed the indices to be removed in an array
new_arr = [val for i, val in enumerate(arr) if all(i != indices)]
print(new_arr)

# OUTPUT --> [10, 30, 50]

Bonus: Delete a Specific Element from a 2D Array in Python

Example 1: Deleting a Row

import numpy as np

print("Input Matrix:")
arr = np.arange(10, 22)
matrix = arr.reshape(3,4)
print(matrix)
print("\nOutput Matrix:")
# deleting elements from 10 till 13, i.e, row 1.
new_matrix = np.delete(matrix, 0, axis=0)
print(new_matrix)

Output:

Input Matrix:
[[10 11 12 13]
 [14 15 16 17]
 [18 19 20 21]]

Output Matrix:
[[14 15 16 17]
 [18 19 20 21]]

Example 2: Deleting a Column

import numpy as np

print("Input Matrix:")
arr = np.arange(10, 22)
matrix = arr.reshape(3, 4)
print(matrix)
print("\nOutput Matrix:")
# deleting the first column
new_matrix = np.delete(matrix, 0, axis=1)
print(new_matrix)

Output:

Input Matrix:
[[10 11 12 13]
 [14 15 16 17]
 [18 19 20 21]]

Output Matrix:
[[11 12 13]
 [15 16 17]
 [19 20 21]]

Recommended: How To Create a Two Dimensional Array in Python?

Conclusion

Let’s wrap things up. The most convenient way to remove an element from a Numpy array is to use the Numpy libraries delete() method. The other approaches explained in this tutorial can also be followed to get the desired output. Feel free to use the one that suits you.

Please subscribe and stay tuned for more solutions and interesting tutorials in the future. Happy learning! πŸ™‚


Do you want to become a NumPy master? Check out our interactive puzzle book Coffee Break NumPy and boost your data science skills! (Amazon link opens in new tab.)

Coffee Break NumPy