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 programmingrandom python filesuntitled4.py", line 15, in <module>
    X_new = np.insert(X,i,0)

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

  File "D:spyderpkgsnumpylibfunction_base.py", line 4560, in insert
    "size %i" % (obj, axis, N))

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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 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)

Method 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)

Method 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)


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x