我试图使用花哨的索引尽快从大型numpy数组中获取切片。我很乐意回复一个观点,但advanced indexing returns a copy。
玩具数据:
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 take:
%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
答案 0 :(得分:6)
用视图无法做到这一点。视图需要一致的步幅,而您的数据随机分散在整个原始数组中。