Skip to main content
 首页 » 编程设计

python之numpy 中的快速高级索引

2025年05月04日15kenshinobiy

我正在尝试使用花式索引尽快从大型 numpy 数组中取出一个切片。我很乐意返回一个 View ,但是 advanced indexing returns a copy .

我已经尝试了来自 here 的解决方案和 here到目前为止没有快乐。

玩具数据:

data = np.random.randn(int(1e6), 50) 
keep = np.random.rand(len(data))>0.5 

使用默认方法:

%timeit data[keep]  
10 loops, best of 3: 86.5 ms per loop 

Numpy 采取:

%timeit data.take(np.where(keep)[0], axis=0) 
%timeit np.take(data, np.where(keep)[0], axis=0) 
10 loops, best of 3: 83.1 ms per loop 
10 loops, best of 3: 80.4 ms per loop     

方法来自 here :

rows = np.where(keep)[0] 
cols = np.arange(a.shape[1]) 
%timeit (a.ravel()[(cols + (rows * a.shape[1]).reshape((-1,1))).ravel()]).reshape(rows.size, cols.size) 
10 loops, best of 3: 159 ms per loop 

而如果您正在查看相同大小的 View :

%timeit data[1:-1:2, :] 
1000000 loops, best of 3: 243 ns per loop 

请您参考如下方法:

没有办法用 View 来做到这一点。 View 需要一致的步幅,而您的数据随机分散在整个原始数组中。