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)
归档时间: |
|
查看次数: |
651 次 |
最近记录: |