Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy: Indexing over the last axis when you don't know the rank in advance

Tags:

How can I index the last axis of a Numpy array if I don't know its rank in advance?

Here is what I want to do: Let a be a Numpy array of unknown rank. I want the slice of the last k elements of the last axis.

If a is 1D, I want

b = a[-k:]

If a is 2D, I want

b = a[:, -k:]

If a is 3D, I want

b = a[:, :, -k:]

and so on.

I want this to work regardless of the rank of a (as long as the rank is at least 1).

The fact that I want the last k elements in the example is irrelevant of course, the point is that I want to specify indices for whatever the last axis is when I don't know the rank of an array in advance.

like image 802
Alex Avatar asked Mar 20 '17 23:03

Alex


People also ask

How do I select the last row of a NumPy array?

Slice One-dimensional Numpy Arrays If you to select the last element of the array, you can use index [11] , as you know that indexing in Python begins with [0] .

What is NumPy fancy indexing?

Fancy indexing is conceptually simple: it means passing an array of indices to access multiple array elements at once. For example, consider the following array: import numpy as np rand = np. random. RandomState(42) x = rand.

How does NumPy calculate rank?

Code. In the example below, the NumPy array is ranked using the argsort() method. The ranks[temp] = np. arange(len(array)) function is used to rank every element in the array.


1 Answers

b = a[..., -k:]

This is mentioned in the docs.

like image 115
user2357112 supports Monica Avatar answered Oct 16 '22 04:10

user2357112 supports Monica