'How to insert zero in an array at that index, which is exceeding the size of that array?

I want to insert zero at certain locations in an array, but the index position of the location exceeds the size of the array

I wanted that as the numbers get inserted one by one, size also gets increased in that process (of the array X), so till it reaches index 62, it will not produce that error.

import numpy as np

X = np.arange(0,57,1)

desired_location = [ 0,  1, 24, 25, 26, 27, 62, 63]

for i in desired_location:
    X_new = np.insert(X,i,0)
print(X_new)

output

File "D:\python programming\random python files\untitled4.py", line 15, in <module>
    X_new = np.insert(X,i,0)

  File "<__array_function__ internals>", line 6, in insert

  File "D:\spyder\pkgs\numpy\lib\function_base.py", line 4560, in insert
    "size %i" % (obj, axis, N))

IndexError: index 62 is out of bounds for axis 0 with size 57




Solution 1:[1]

Make a copy of X into X_new so the array gets longer in loop as you desire.

X_new = X.copy()
for i in desired_location:
    X_new = np.insert(X_new, i, 0)

Solution 2:[2]

how silly I was.

import numpy as np

X = np.arange(0,57,1)

desired_location = [ 0,  1, 24, 25, 26, 27, 62, 63]



for i in desired_location:
    X = np.insert(X,i,0)
    
print(X)

Solution 3:[3]

Converting tolist(), inserting and converting to np.array is an order of magnitude faster.

# %%timeit 10000 loops, best of 5: 117 µs per loop
X_new = X
for i in desired_location:
    X_new = np.insert(X_new,i,0)
# %%timeit 100000 loops, best of 5: 4.18 µs per loop
X_new = X.tolist()
for i in desired_location:
    X_new.insert(i, 0)
np.fromiter(X_new, dtype=X.dtype)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Tim gallerge
Solution 3