numpy中的快速高级索引

dgm*_*p88 1 python arrays indexing optimization numpy

我正试图使用​​花哨的索引尽快从大型numpy数组中获取切片.我很乐意返回一个视图,但高级索引会返回一个副本.

到目前为止,我已经尝试过来自这里这里的解决方案.

玩具数据:

data = np.random.randn(int(1e6), 50)
keep = np.random.rand(len(data))>0.5
Run Code Online (Sandbox Code Playgroud)

使用默认方法:

%timeit data[keep] 
10 loops, best of 3: 86.5 ms per loop
Run Code Online (Sandbox Code Playgroud)

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    
Run Code Online (Sandbox Code Playgroud)

方法从这里:

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
Run Code Online (Sandbox Code Playgroud)

如果您正在观看相同大小的视图:

%timeit data[1:-1:2, :]
1000000 loops, best of 3: 243 ns per loop
Run Code Online (Sandbox Code Playgroud)

use*_*ica 6

用视图无法做到这一点.视图需要一致的步幅,而您的数据随机分散在整个原始数组中.