Reputation: 11
I am trying to insert 3 consecutive zeroes at each alternate position in the given array. This works fine with a list but not with the array as when I run the for loop it does not save it inside the array but just prints it for the time
var = [1,2,3,4,5]
n = 0
for j in range(4):
for i in range(3):
n = n+1
var.insert(n,0)
n=n+1
print(var)
zero_3 = np.zeros(3)
var2 = np.array([1,2,3,4,5])
for n in range(1,5):
print(var2)
print(np.insert(var2,n,zero3))
print(var2)
n=n+3
#Output when I run it shows this:
#var
#[1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0, 5]
#var2 for all lines below
#[1 2 3 4 5]
#[1 0 0 0 2 3 4 5]
#[1 2 3 4 5]
#[1 2 3 4 5]
#[1 2 0 0 0 3 4 5]
#[1 2 3 4 5]
#[1 2 3 4 5]
#[1 2 3 0 0 0 4 5]
#[1 2 3 4 5]
#[1 2 3 4 5]
#[1 2 3 4 0 0 0 5]
#[1 2 3 4 5]
Upvotes: 1
Views: 86
Reputation: 2364
what you want to do is actually called padding, and there is an off-the-shelf function for you to use, like np.pad
.
var = np.arange(5) + 1 # -> array([1, 2, 3, 4, 5])
var = var.reshape(5 ,1) # -> array([[1],[2],[3],[4],[5]])
var = np.pad(var, ((0,0), (0,3)), mode='constant',constant_values=0)
var = var.reshape(-1) # to flattern the tensor, make it a rank-1 array, after executing this line, var should be like array([1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0, 5, 0, 0, 0])
# if you don't want the last 3 zeros, do:
var = var[:-3]
the basic usage of np.pad
is
np.pad(var, ((left1, right1), (left2,right2)),mode='constant',constant_values=0)
where var
is rank 2 tensor with shape [A, B]
, and the returned tensor is with shape [A + left1 + right1, B + left2 + right2]
.
the meaning of left1, right1, left2, right2, A, B
can be explained by this picture:
It's easy to generalize the formula to rank-n tensor. But for simplicity, I only write rank-2 tensor as an example.
see numpy.pad for more sophisticated usage.
Upvotes: 1
Reputation: 231375
In [87]: var2 = np.array([1,2,3,4,5])
In [88]: np.insert(var2,[1,2,3,4],[0])
Out[88]: array([1, 0, 2, 0, 3, 0, 4, 0, 5])
In [94]: np.insert(var2,[1,1,1,2,2,2,3,3,3,4,4,4],0)
Out[94]: array([1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0, 5])
In [96]: np.insert(var2,np.repeat(np.arange(1,5),3),0)
Out[96]: array([1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0, 5])
Under the covers insert
is just doing:
In [97]: res = np.zeros((var2.shape[0]+3*(var2.shape[0]-1)), dtype=var2.dtype)
In [98]: res[::4]=var2
In [99]: res
Out[99]: array([1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0, 5])
Upvotes: 1