'Delete elements from Numpy array

I want to delete all the elements from a Numpy array except the last element and return the Numpy array. For eg: arr = np.array([4, 5, 6, 7, 8, 9, 10, 11]) Output should be:: arr = [11]

Please let me know how can I achieve this.



Solution 1:[1]

We can slice using -1 to start from the last item.

import numpy as np

arr = np.array([4, 5, 6, 7, 8, 9, 10, 11]) 
last_arr = arr[-1:]
print (last_arr)

gives

[11]

We can use arr[-1] to get the value of the last element, but it gives us the value 11 and not as an array [11] as you want. We can then create a new array, but this is a longer way to do it.

Solution 2:[2]

You can simply write:

arr[-1] # This is the last element

so you can assign something this way:

arr = np.array([arr[-1]]) # A numpy.array containing only the last element of the other one

Otherwise, if you only want a list containing the last element:

new = [arr[-1]]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2