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?
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]
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)
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?
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]
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)