Remove specific elements from a NumPy 1D array

Deleting element from NumPy array using np.delete()

The delete(array_name ) method will be used to do the same. Where array_name is the name of the array to be deleted and index-value is the index of the element to be deleted. For example, if we have an array with 5 elements, The indexing starts from 0 to n-1. If we want to delete 2, then 2 element index is 1. So, we can specify If we want to delete multiple elements i.e. 1,2,3,4,5 at a time, you can specify all index elements in a list.

Remove a Specific element in a 1D array

Program to create an array with 5 elements and delete the 1st element.

Python3




# import numpy as np
import numpy as np
 
# create an array with 5 elements
a = np.array([1, 2, 3, 4, 5])
 
# display a
print(a)
 
# delete 1 st element
print("remaining elements after deleting 1st element ",
      np.delete(a, 0))


Output:

[1 2 3 4 5]
remaining elements after deleting 1st element  [2 3 4 5]

Remove Multiple elements  in a 1D array

Program to create an array with 5 elements and delete the 1st and last element.

Python3




# import numpy as np
import numpy as np
 
# create an array with 5
# elements
a = np.array([1, 2, 3, 4, 5])
 
# display a
print(a)
 
# delete 1st element and 5th element
print("remaining elements after deleting 1st and last element ",
      np.delete(a, [0, 4]))


Output:

[1 2 3 4 5]
remaining elements after deleting 1st and last element  [2 3 4]

Remove a Specific NumPy Array Element by Value in a 1D array

Removing 8 values from an array.

Python3




import numpy as np
arr_1D = np.array([1 ,2, 3, 4, 5, 6, 7, 8])
 
arr_1D = np.delete(arr_1D, np.where(arr_1D == 8))
print(arr_1D)


Output:

[1 2 3 4 5 6 7]

Removing multiple elements from a NumPy using an index

Pass an array containing the indexes of all the elements except the index of the element to be deleted, This will delete the element from the array.

Python3




import numpy as np
# numpy array
arr = np.array([9, 8, 7, 6, 5, 4, 3, 2, 1])
 
# index array with index of all the elements, except index = 5.
# so element at 5th index will be deleted.
indexArray = [0, 1, 2, 3, 4, 6, 7, 8]
 
# passing indexarray to the array as index
arr = arr[indexArray]
 
print(arr)


Output:

[9 8 7 6 5 3 2 1]

How to remove specific elements from a NumPy array ?

In this article, we will discuss how to remove specific elements from the NumPy Array. 

Similar Reads

Remove specific elements from a NumPy 1D array

Deleting element from NumPy array using np.delete()...

Remove specific elements from a NumPy 2D array

...