我想按行数移动每一行,并相对于我想要的输出形状。一个例子:
array([[0, 1, 2], array([[0, 1, 2], array([[0, 1, 2, 0, 0],
[1, 2, 3], -> [1, 2, 3], -> [0, 1, 2, 3, 0],
[2, 3, 4]]) [2, 3, 4]]) [0, 0, 2, 3, 4])
最左边的数组是我的输入,最右边的数组是我们想要的输出。这可以推广到更大的阵列,例如10x10
阵列。
有什么好方法吗?
我拥有的是:
A = np.array([[1, 2, 3],
[2, 3, 4],
[3, 4, 5]], dtype=np.float32)
out = np.zeros((A.shape[0], A.shape[1]*2-1))
out[[np.r_[:3]], [np.r_[:3] + np.r_[:3][:,None]]] = A
这里有一个快速的方法:
def f(a):
r, _ = a.shape
return np.c_[a, np.zeros((r, r), dtype=a.dtype)].ravel()[:-r].reshape(r, -1)
示例:
a = np.arange(8).reshape(4, -1)
>>> f(a)
array([[0, 1, 0, 0, 0],
[0, 2, 3, 0, 0],
[0, 0, 4, 5, 0],
[0, 0, 0, 6, 7]])
定时
a = np.random.randint(100, size=(1000, 1000))
%timeit f(a)
# 2.08 ms ± 14.5 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
以下是n大小的方阵的解决方案。
np.concatenate((A,np.zeros((n,n))),axis=1).flatten()[0:-n].reshape([n,2*n-1])