删除2D矩阵的最后一列或一维向量的最后一个元素 [英] Remove last column of 2D matrix, or last element of 1D vector
问题描述
我有一个功能:
remove_last(x):
如果x
是一维矢量,那么我希望它删除其中的最后一个元素.
有时x
可能是我要从中删除最后一个元素的矢量矩阵.
在这种情况下,我需要删除最后一列.
if x
is a 1D vector, then I want it to remove the last element in it.
sometime x
might be a matrix of such vector that I want the last element removed from.
In which case I need to remove the last column.
使用示例:
aa = np.asarray([1,2,3])
print remove_last(aa)
#Output: [1 2]
bb = np.asarray([aa,2*aa,3*aa,4*aa])
print remove_last(aa)
#Output: [[1 2], [2 4], [3 6], [4 8]]
到目前为止,我有:
def remove_last(x):
assert(x.ndim<=2)
if x.ndim==1:
return x[:-1]
else:
return x[:,:-1]
可以,但是不是很好.
使用numpy著名的切片技师,一定有更好的方法
There must be a better way, using numpy's famous slicing mechanic
推荐答案
有.
您正在寻找的是...
省略号切片标记.
它说:填充许多:
,直到切片说明符的数量与数组的维数匹配为止."
There is.
What you are looking for is the ...
ellipsis slicing marker.
It says "Fill in a number of :
until the number of slicing specifiers matches the dimension of the array."
这样,您的代码将变为:
With that your code becomes:
def remove_last(x):
return x[...,:-1]
清洁和pythonic.
Clean and pythonic.
这篇关于删除2D矩阵的最后一列或一维向量的最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!