Skip to content
Related Articles

Related Articles

Improve Article

How to remove specific elements from a NumPy array ?

  • Last Updated : 21 Apr, 2021

In this article, we will discuss how to remove specific element from the NumPy Array. The delete() method will be used to do the same.

Syntax:

numpy.delete(array_name,index_value)

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, we are having an array with 5 elements, 



array1=[1,2,3,4,5]

The indexing starts from 0 to n-1. If we want to delete 2, then 2 element index is 1. So, we can specify 

np.delete(array1,1)

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.

np.delete(array1,[0,1,2,3,4])

Below are some examples where we remove specific elements in a NumPy array. 

Example 1:

Program to create an array with 5 elements and delete 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]

Example 2:



Program to create an array with 5 elements and delete 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 1 st 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]

Example 3:

Deleting 4th element.

Python3




#import numpy as np
import numpy as np
  
# create an array with 10 elements
a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
  
# display a
print(a)
  
# delete  4 th  element
print("remaining elements after deleting 4th element ",
      np.delete(a, 3))

Output:

[ 1  2  3  4  5  6  7  8  9 10]

remaining elements after deleting 4th element  [ 1  2  3  5  6  7  8  9 10]

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :