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

以下是第一个答案:

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

注意,a[[slice(0, id) for id in idx]]np.__version__ = 1.19.4一起使用以下FutureWarning:

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

最新更新