Delete the last column of a 2D matrix or the last element of a 1D vector

I have a function:

remove_last(x):

if x is a 1D vector, then I want it to remove the last element in it. sometime x may be the matrix of such a vector from which I want to remove the last element. In this case, I need to delete the last column.

Usage example:

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

So far, I:

 def remove_last(x): assert(x.ndim<=2) if x.ndim==1: return x[:-1] else: return x[:,:-1] 

which works, but it's not very nice.

There must be a better way using the famous numpy chopping mechanic

0
source share
1 answer

There is. What you are looking for is a marker ... ellipse. It says: "Fill the row : until the number of cut specifiers matches the size of the array."

The code will look like this:

 def remove_last(x): return x[...,:-1] 

Clean and python.

+3
source

Source: https://habr.com/ru/post/986944/


All Articles