2017-07-17 18 views
1

目前我访问多个片段如下:你如何有效地从numpy的数组访问多个切片

首先,我分配将被重新分配数组多次

X = np.zeros((batch_size, window, 5)) 

这是将运行多次分配回路(batch_indices有不同的索引每次但相同的形状):

for i, b in enumerate(batch_indices): 
    X[i] = Xs[b:b+window] 

有没有更有效的方法?我觉得好像有应语法类似于:

X = Xs[ [slice(b,b+window) for b in batch_indices] ] 

虽然Xs形状为2维的,X的最终形状应该是一个3维np.array。可以这样想:Xs是一个长时间多维时间序列,X需要是一个包含多维时间序列切片的numpy数组。

+0

你看过[numpy迭代](https://docs.scipy.org/doc/numpy/reference/arrays.nditer.html)吗? –

+0

你有尝试布尔索引吗?值得进行性能检查...... – Raf

+0

发布的解决方案是否适合您? – Divakar

回答

2

方法#1

一个量化的方法是创建所有的滑动窗口索引和索引Xs这些,像这样 -

X = Xs[np.asarray(batch_indices)[:,None] + np.arange(window)] 

方法2

另一种有效的记忆方法是创建sliding-windowsnp.lib.stride_tricks.as_strided,从而避免了滑动窗口指数发展在之前的做法,只是做指数与batch_indices,像这样 -

X = strided_axis0(Xs,window)[np.asarray(batch_indices)] 

跨越式发展基于功能strided_axis0here