numpy.insert(arr, obj, values, axis=None)
Insert values along the given axis before the given indices.
Official Document
arr: array_like
Input array.
obj: int, slice or sequence of ints
Object that defines the index or indices before which values is inserted.
values: array_like
Values to insert into arr. If the type of values is different from that of arr
axis: int, optional
Axis along which to insert values. If axis is None then arr is flattened first.
在对arr
在axis
维度进行切片,然后在obj
所指定的index之前插入values
示例1. 输入为一维向量
在向量 [1,2,3,4] 的第1个元素前面的位置插入5
print(np.insert([1,2,3,4],1,5))
[1 5 2 3 4]
在向量 [1,2,3,4] 的第1个元素前面的位置插入5,第2个元素前面的位置插入7
print(np.insert([1,2,3,4],[1,2],[5,7]))
[1 5 2 7 3 4]
示例2. 输入为矩阵
插入一整行
import numpy as np
a = a = np.array([[1, 1], [2, 2], [3, 3]])
print('a=',a)
print('after insertion:\n',np.insert(a,[1],[6,6],axis=0))
结果
a= [[1 1]
[2 2]
[3 3]]
after insertion:
[[1 1]
[6 6]
[2 2]
[3 3]]
插入一整列
import numpy as np
a = a = np.array([[1, 1], [2, 2], [3, 3]])
print('a=',a)
print('after insertion:\n',np.insert(a,[1],[[6],[6],[6]],axis=1))
结果
a= [[1 1]
[2 2]
[3 3]]
after insertion:
[[1 6 1]
[2 6 2]
[3 6 3]]