[英]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.我想从 Numpy 数组中删除除最后一个元素之外的所有元素并返回 Numpy 数组。 For eg: arr = np.array([4, 5, 6, 7, 8, 9, 10, 11]) Output should be:: arr = [11]
例如:arr = np.array([4, 5, 6, 7, 8, 9, 10, 11]) Output 应该是:: arr = [11]
Please let me know how can I achieve this.请让我知道我怎样才能做到这一点。
We can slice using -1 to start from the last item.我们可以使用 -1 从最后一项开始切片。
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.我们可以使用
arr[-1]
来获取最后一个元素的值,但它给我们的值是11
而不是你想要的数组[11]
。 We can then create a new array, but this is a longer way to do it.然后我们可以创建一个新数组,但这是一种更长的方法。
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:否则,如果您只想要一个包含最后一个元素的
list
:
new = [arr[-1]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.