How to remove an element from a NumPy array in Python

You can remove an element from a NumPy array in Python with the following code. If you want to learn Python, I highly recommend reading This Book.

Example 1: Remove Single Element from NumPy array

# Import the NumPy library as np
import numpy as np

# Initialize the NumPy array
a = np.array([5, 10, 15, 20, 25, 30])

# Remove 3rd element from NumPy array
b = np.delete(a, 2)

# Display the Number of Zeros
print(b)

Output:

[ 5 10 20 25 30]

Example 2: Remove multiple elements from NumPy array

# Import the NumPy library as np
import numpy as np

# Initialize the NumPy array
a = np.array([5, 10, 15, 20, 25, 30, 35, 40, 45, 50])

# Remove 3rd and 5th element from NumPy array
index = [2, 4]
b = np.delete(a, index)

# Display the Number of Zeros
print(b)

Output:

[ 5 10 20 30 35 40 45 50]

Free Learning Resources

Leave a Comment

Your email address will not be published.