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
CodePudding user response:
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)
CodePudding user response:
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)
CodePudding user response:
Converting to tolist()
, inserting and converting to np.array
is orders 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)