我将以下MATLAB代码转换为Python:
function segments = segmentSlidingWindow(data, wSize, sSize)
len = size(data,1);
wCurr = 1;
segments = []; % todo: init to make faster
while (wCurr<len-wSize)
segments = [segments; wCurr wCurr+wSize]; % start stop
wCurr = wCurr+sSize; % step forward
end
segments = [segments; wCurr len]; % add residual
end
我在Numpy for Matlab users guide
之后编写了以下Python代码def sliding_window(data, window_size, step_size):
length = data.shape[0]
wCurr = 0
segments = []
while wCurr < length - window_size:
segments = np.vstack([np.hstack([segments]), np.hstack([wCurr, window_size + wCurr])])
wCurr = wCurr + step_size
segments = np.vstack([np.hstack([segments]), np.hstack([wCurr, length])])
plt.plot(segments)
plt.show()
return segments
我还会绘制分段数据以查看其外观。但是,我不能运行这个Python代码,因为在线:
segments = np.vstack([np.hstack([segments]), np.hstack([wCurr, window_size + wCurr])])
我收到以下错误:
ValueError: all the input array dimensions except for the concatenation axis must match exactly
当我打印length
时,我得到504
我的数据是一个包含5列的pandas DataFrame。我只想在中间三列上有一个滑动窗口,因为它们是唯一相关的。第一列是时间戳,最后一列是标签。
wSize
和sSize
是整数。
我想为这样的事情制作一个滑动窗口:
1495573445.162, 0, 0.021973, 0.012283, -0.995468, 1
1495573445.172, 0, 0.021072, 0.013779, -0.994308, 1
1495573445.182, 0, 0.020157, 0.015717, -0.995575, 1
1495573445.192, 0, 0.017883, 0.012756, -0.993927, 1
1495573445.202, 0, 0.021194, 0.012161, -0.994705, 1
1495573445.212, 0, 0.019638, 0.013718, -0.994019, 1
1495573445.222, 0, 0.019440, 0.010803, -0.994476, 1
1495573445.232, 0, 0.018112, 0.010849, -0.993073, 1
1495573445.242, 0, 0.020157, 0.011154, -0.994644, 1
1495573445.252, 0, 0.020340, 0.010040, -0.995804, 1
1495573445.262, 0, 0.017792, 0.009857, -0.996078, 1
1495573445.272, 0, 0.020538, 0.010239, -0.994858, 1
其中输出为滚动窗口,步长为窗口大小的一半。
答案 0 :(得分:1)
我有一种感觉,你很可能想用这样的东西替换你的while
循环:
s = np.arange(0, length - window_size, step_size)
segments = np.vstack([s, s + window_size]).T
length = 15; step_size = 3; window_size = 6;
段的内容如下:
array([[ 0, 6],
[ 3, 9],
[ 6, 12]])
如果您想要转置的答案,请在上述代码中的.T
后删除vstack
,获取:
array([[ 0, 3, 6],
[ 6, 9, 12]])
如果你真的坚持使用while
循环,那么:
segments = np.empty((0, 2), dtype=np.int)
while wCurr < length - window_size:
segments = np.vstack([segments, [wCurr, window_size + wCurr]])
wCurr = wCurr + step_size
或:
segments = np.empty((0, 2), dtype=np.int)
while wCurr < length - window_size:
segments = np.append(segments, [[wCurr, window_size + wCurr]], axis=0)
wCurr = wCurr + step_size