Home > database >  Delete elements from Numpy array
Delete elements from Numpy array

Time:04-20

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.

CodePudding user response:

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.

CodePudding user response:

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]]
  • Related