Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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

This is mentioned in the docs.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!