如何在该索引处的数组中插入零,这超出了该数组的大小?
How to insert zero in an array at that index, which is exceeding the size of that array?
我想在数组中的某些位置插入零,但是该位置的索引位置超出了数组的大小
我希望当数字被一个一个地插入时,大小也会在那个过程中增加(数组 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
将 X
的副本复制到 X_new
中,这样数组可以根据需要在循环中变长。
X_new = X.copy()
for i in desired_location:
X_new = np.insert(X_new, i, 0)
我当时真傻。
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)
转换 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)
我想在数组中的某些位置插入零,但是该位置的索引位置超出了数组的大小
我希望当数字被一个一个地插入时,大小也会在那个过程中增加(数组 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
将 X
的副本复制到 X_new
中,这样数组可以根据需要在循环中变长。
X_new = X.copy()
for i in desired_location:
X_new = np.insert(X_new, i, 0)
我当时真傻。
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)
转换 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)