Numpy срез до заданного тензора

#python #numpy #slice

#python #numpy #срез

Вопрос:

Есть ли способ избежать явного разделения с массивом индексов? Я попытался посмотреть np.s_ , но не могу найти решение

MWE:

 a = np.random.rand(3, 4, 5)
idx = np.array([2, 2, 3])
expected_result = a[:idx[0], :idx[1], :idx[2]]

a[:idx]
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: only integer scalar arrays can be converted to a scalar index
  

Ответ №1:

Вот первый ответ:

 a[tuple([slice(0, id) for id in idx])]
  

Обратите внимание, что это a[[slice(0, id) for id in idx]] работает со следующим предупреждением о будущем с np.__version__ = 1.19.4 :

 FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated;
use `arr[tuple(seq)]` instead of `arr[seq]`.
In the future this will be interpreted as an array index,
`arr[np.array(seq)]`, which will result either in an error or a different result