Delete multiple selected elements from NumPy array in Python

In this tutorial, you will learn how you can delete multiple selected elements from the NumPy array in Python.

Deleting Single element

For this, First, we have to import the Numpy module

import numpy as np

Let us take an array first so that you can apply different methods to it and we can do that by writing:

sample_array = np.array([1,2,3,4,5,6,7])

Now that you have an array you can finally begin to learn how you can delete multiple items from it. For this purpose, we are going to use delete() function which will take the array and the element that is to be deleted, as an argument. For this example, let us assume that we want to delete an element from index 3, we can do that by using:

sample_array = np.delete(sample_array, 3)
print(sample_array)

This will delete the element from the third index of the sample array and the output of the above code will be:

[1 2 3 5 6 7]

As you can see, the element from the third position, i.e element 4, has been deleted.

Deleting Multiple elements

Now if you want to delete elements from multiple positions in the above array using their index position, you can do that by writing the code as:

sample_array = np.delete(sample_array, [3,4,5])
print(sample_array)

Output for the above code will be:

[1 2 3]

Here, as we can see, the elements from index 3, 4 and 5 have been deleted from the sample array. In this way, you can delete elements from different selected positions of a Numpy array.

Leave a Reply

Your email address will not be published. Required fields are marked *