我想在陣列的某些位置插入零,但是該位置的索引位置超過了陣列的大小
我希望隨著數字一一插入,在該程序中(陣列 X)大小也會增加,所以直到它達到索引 62,它不會產生該錯誤。
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)
輸出
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
uj5u.com熱心網友回復:
X制作into的副本,X_new以便陣列根據需要在回圈中變長。
X_new = X.copy()
for i in desired_location:
X_new = np.insert(X_new, i, 0)
uj5u.com熱心網友回復:
我是多么愚蠢。
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)
uj5u.com熱心網友回復:
轉換tolist()、插入和轉換為np.array快一個數量級。
# %%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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/468590.html
