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.
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.
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.