我需要在numpy数组的备用行和列中插入任意数量的零。例如,假设我们要在所有备用列和行中插入1个零。
Input => [[ 1,2,3],
[ 4,5,6],
[ 7,8,9]]
output => [[ 1,0,2,0,3],
[ 0,0,0,0,0],
[ 4,0,5,0,6],
[ 0,0,0,0,0],
[ 7,0,8,0,9]]
我知道如何通过使用循环来实现这一点,但我不确定这是否是最有效的方法,或者是否有可能实现某些矢量化实现。
答案 0 :(得分:4)
使用zeros-initialization
并使用步长大小切片进行分配的一种方法 -
def insert_zeros(a, N=1):
# a : Input array
# N : number of zeros to be inserted between consecutive rows and cols
out = np.zeros( (N+1)*np.array(a.shape)-N,dtype=a.dtype)
out[::N+1,::N+1] = a
return out
样品运行 -
In [167]: a
Out[167]:
array([[83, 87, 19, 24],
[28, 24, 24, 77],
[26, 87, 57, 37]])
In [168]: insert_zeros(a, N=1)
Out[168]:
array([[83, 0, 87, 0, 19, 0, 24],
[ 0, 0, 0, 0, 0, 0, 0],
[28, 0, 24, 0, 24, 0, 77],
[ 0, 0, 0, 0, 0, 0, 0],
[26, 0, 87, 0, 57, 0, 37]])
In [169]: insert_zeros(a, N=2)
Out[169]:
array([[83, 0, 0, 87, 0, 0, 19, 0, 0, 24],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[28, 0, 0, 24, 0, 0, 24, 0, 0, 77],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[26, 0, 0, 87, 0, 0, 57, 0, 0, 37]])