How to remove last element from NumPy array

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

Method 1: Remove last element from NumPy array using slicing

# 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 last element from NumPy array
b = a[:-1]

# Display the array after removing last element
print(b)

Output:

[ 5 10 15 20 25 30 35 40 45]

Method 2: Remove last element from NumPy array using np.arange()

# 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 last element from NumPy array
b = a[np.arange(a.size - 1)]

# Display the array after removing last element
print(b)

Output:

[ 5 10 15 20 25 30 35 40 45]

Method 3: Remove last element using np.delete()

# 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 last element from NumPy array
b = np.delete(a, -1)

# Display the array after removing last element
print(b)

Output:

[ 5 10 15 20 25 30 35 40 45]

Method 4: Remove last element using np.resize()

# 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 last element from NumPy array
b = np.resize(a, a.size - 1)

# Display the array after removing last element
print(b)

Output:

[ 5 10 15 20 25 30 35 40 45]

Free Learning Resources

Leave a Comment

Your email address will not be published.