w3resource

NumPy: Remove specific elements in a NumPy array

NumPy: Array Object Exercise-89 with Solution

Write a NumPy program to remove specific elements from a NumPy array.

Pictorial Presentation:

Python NumPy: Remove specific elements in a NumPy array

Sample Solution:

Python Code:

# Importing the NumPy library and aliasing it as 'np'
import numpy as np

# Creating a NumPy array 'x' containing integers
x = np.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 100])

# Creating a list 'index' containing indices of elements to be deleted from array 'x'
index = [0, 3, 4]

# Printing a message indicating the original array will be displayed
print("Original array:")

# Printing the original array 'x' with its elements
print(x)

# Printing a message indicating the deletion of elements at specified indices
print("Delete first, fourth and fifth elements:")

# Deleting elements from array 'x' at the specified indices mentioned in the 'index' list
# The resulting array 'new_x' contains elements of 'x' after deletion
new_x = np.delete(x, index)

# Printing the modified array 'new_x' after deleting elements at specified indices
print(new_x) 

Sample Output:

Original array:                                                        
[ 10  20  30  40  50  60  70  80  90 100]                              
Delete first, fourth and fifth elements:                               
[ 20  30  60  70  80  90 100]

Explanation:

In the above code –

x = np.array(...) – This line creates a NumPy array 'x' with the given elements.

index = [0, 3, 4]: Define a list 'index' containing the indices of the elements we want to delete from the array 'x'.

new_x = np.delete(x, index): Use the np.delete() function to delete the elements from 'x' at the specified indices. The result is a new array 'new_x' with the specified elements removed.

Python-Numpy Code Editor:

Previous: Write a NumPy program to replace all elements of NumPy array that are greater than specified array.
Next: Write a NumPy program to replace the negative values in a NumPy array with 0.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.