Skip to main content
 首页 » 编程设计

python之numpy take 无法使用切片进行索引

2025年05月04日16jyk

根据 take 的 numpy 文档 它与“花式”索引(使用数组索引数组)做同样的事情。但是,如果您需要沿着给定轴的元素,它会更容易使用。

但是,与“花式”或常规 numpy 索引不同,似乎不支持使用切片作为索引:

In [319]: A = np.arange(20).reshape(4, 5) 
 
In [320]: A[..., 1:4] 
Out[320]:  
array([[ 1,  2,  3], 
       [ 6,  7,  8], 
       [11, 12, 13], 
       [16, 17, 18]]) 
 
In [321]: np.take(A, slice(1, 4), axis=-1) 
TypeError: long() argument must be a string or a number, not 'slice' 

使用仅在运行时已知的轴上的切片来索引数组的最佳方法是什么?

请您参考如下方法:

最有效的方法似乎是 A[(slice(None),) * axis + (slice(1, 4),)]:

In [19]: import numpy as np 
    ...: x = np.random.normal(0, 1, (50, 50, 50)) 
    ...: s = slice(10, 20) 
    ...: axis = 2 
    ...:  
    ...:  
 
In [20]: timeit np.rollaxis(np.rollaxis(x, axis, 0)[s], 0, axis + 1) 
2.32 µs ± 15.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) 
 
In [21]: timeit x.take(np.arange(x.shape[axis])[s], axis) 
28.5 µs ± 38.2 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) 
 
In [22]: timeit x[(slice(None),) * axis + (s,)] 
321 ns ± 0.341 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)