从给定的numpy数组[1,2,3,4]和窗口wz=2(每个元素前后两个元素)中,我必须得到一些对(中央元素,窗口中的元素)进行操作。 不存在元素的对可以跳过或替换为零。 所以在这个例子中,我必须得到以下结果:
[[1., 0.]
[2., 1.]
[3., 2.]
[4., 3.]
[1., 2.]
[2., 3.]
[3., 4.]
[4., 0.]
[1., 0.]
[2., 0.]
[3., 1.]
[4., 2.]
[1., 3.]
[2., 4.]
[3., 0.]
[4., 0.]]
我的实现非常低效,看起来像这样:
x = np.array([1,2,3,4])
l = x.shape[0]
for i in range(1, m):
init = np.empty((x.shape[0]*2,2))
init[:,0] = np.append(x, x)
init[:l,1] = np.pad(x, (i,0), mode='constant')[:l]
init[-l:,1] = np.pad(x, (0,i), mode='constant')[-l:]
corpus.extend(init)
请问有人能提供更高效的解决方案吗? 在其他我实现过的简单测试数据和变量上,我得到了以下结果:
285 µs ± 19.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
379 µs ± 7.68 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
~
是做什么用的? - erocoar