【发布时间】:2016-12-21 22:46:53
【问题描述】:
我正在尝试使用花哨的索引尽快从大型 numpy 数组中获取切片。我很乐意返回视图,但 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
而如果您正在查看相同大小的视图:
%timeit data[1:-1:2, :]
1000000 loops, best of 3: 243 ns per loop
【问题讨论】:
标签: python arrays numpy optimization indexing