0

I believe it is a simple question, but I am stuck with it. I'm picking specific dimensions from a tensor like

input = x[i, :, 38:44]

Everything was fine until this point, but now I want to extract a different range of dimensions, such as:

38:44 then 46 to 48 then 50 to 54. How can we do this?

Ahmad
  • 645
  • 2
  • 6
  • 21
  • can you check this QA: [Index multiple, non-adjacent ranges in numpy](https://stackoverflow.com/questions/34188620/index-multiple-non-adjacent-ranges-in-numpy)? – mozway Jun 25 '22 at 08:03
  • No its not the one which I want? – Ahmad Jun 25 '22 at 08:13
  • 1
    @mozway's referenced answer should solve this question as well. Please provide a [mre] to clarify what's different in this case. – Michael Szczesny Jun 25 '22 at 08:33

2 Answers2

0

You send a list with the desired indices. For example, consider the following array:

import numpy as np
arr = np.array([[1,2], [2,3], [4,5], [6,7], [8,9]])

We can retrieve indices with the following way:

arr[[0,1,3], :]

Output:

array([[1, 2],
       [2, 3],
       [6, 7]])

Here I created a list of desired indices [0,1,3] and send as retrieve the relevant dimensions.

So as for your question, you get declare whenever indices you want:

desired_indices = list(range(38,44)) + list(range(46,48)) + list(range(50,54))
my_input = x[i, :, desired_indices]

(I also change the "input" from the variable name as it will create a problem)

Roim
  • 2,986
  • 2
  • 10
  • 25
  • Thank you for answer. however, it swapping the dimensions like without this the input shape is `(24, 4)`. However after using `desired_indices = list(range(38, 40)) + list(range(46, 48)) my_input = x[i, :, desired_indices]` reverse shape like `(4, 24)` – Ahmad Jun 25 '22 at 08:37
  • 2
    Then you probably got the dimensions wrong - can't help without full reproducible example. You asked how to retrieve different range of dimensions, and my answer is relevant for that – Roim Jun 25 '22 at 08:38
0

The question of how to take multiple slices has come up often on SO.

If the slices are regular enough you may be able reshape the array, and take just one slice.

But more generally you have 2 options:

  • take the slices separately, and join them (np.concatenate)

  • construct an advanced indexing array, and apply that. If the slices all have the same length you might make the array with linspace or a bit of broadcasted math. But if they differ, you have to concatenate a bunch of arange.

With x[i, :, arr] where arr is an array like np.array([38,39,50,60]), there is a complicating factor that it mixes basic and advanced indexing. It is well known, at least among experienced numpy users, that this gives an unexpected shape, with the slice dimension(s) moved to the end.

x[i][:,arr] is one way around this.

hpaulj
  • 221,503
  • 14
  • 230
  • 353