Inserting values into numpy array based on if condition

Question:

Suppose I have the following array:

a = np.array([1,0,2,3,0,4,5,0])

for each zero I would like to duplicate a zero and add it to the array such that I get:

np.array([1,0,0,2,3,0,0,4,5,0,0])

So I did the following:

for i in range(len(a)):
    if i-1==0 or i==0:
        print(np.insert(a,i,0))

which did not work. I wonder what am I doing wrong?

Asked By: Wiliam

||

Answers:

You need to check if the value in the array is 0, not if the index is 0. When you insert the value you need to consider the changes to the original array. In addition, you need to assign the returned value from insert back to a

a = np.array([1, 0, 2, 3, 0, 4, 5, 0])
    i = 0
    while i < len(a):
        if a[i] == 0:
            a = np.insert(a, i, 0)
            i += 1
        i += 1

print(a) # [1 0 0 2 3 0 0 4 5 0 0]
Answered By: Guy

It can be done without loops by finding the 0‘s related indices and then insert 0 besides them:

inds = np.where(a == 0)[0]
a = np.insert(a, inds, 0)
Answered By: Ali_Sh
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.