NumPy insert()

insert() 方法在给定的轴上的指定索引处添加值。

示例

import numpy as np

# create an array
numbers = np.array([0, 1, 3, 4])

# insert 4 at index 2
array2 = np.insert(numbers, 2, 4)

print(array2)

# Output : [0 1 4 3 4]

在这里,insert() 方法在索引 2 处插入了一个新项 **4**,并将前一项移到了下一个索引。


insert() 语法

insert() 的语法是

numpy.insert(array, obj, values, axis)

insert() 参数

insert() 方法接受四个参数:

  • array - 原始数组
  • obj - 插入值的索引
  • values - 要在给定位置插入的数组
  • axis(可选) - 插入值的轴

insert() 返回值

insert() 方法返回一个插入了值的数组。


示例 1:在给定索引处插入数组

import numpy as np

array1 = np.array([0, 1, 2, 3])
array2 = np.array([4, 5, 6, 7])

# insert values from array2 to array1 before index 2 array3 = np.insert(array1, 2, array2)
print(array3)

输出

[0 1 4 5 6 7 2 3]

示例 2:在不同索引处插入数组元素

我们可以为不同的索引插入不同的值。

import numpy as np

array1 = np.array([0, 1, 2, 3])
array2 = np.array([4, 5, 6, 7])

# insert values from array2 to array1 before given indices array3 = np.insert(array1, [2, 3, 2, 1], array2)
print(array3)

输出

[0 7 1 4 6 2 5 3]

注意:当将一个序列作为 obj 传递时,序列的大小应与值的数量匹配。例如,当插入 **4** 个值时,应提供 **4** 个索引。


示例 3:在给定索引之前向 2-D 数组插入内容

与 1-D 数组类似,值可以沿任何轴插入到 2-D 数组的任何索引处。

import numpy as np

array1 = np.array([[0, 1], [2, 3]])
array2 = np.array([4, 5])

# insert values to an array before index 2 array3 = np.insert(array1, 2, array2)
print('\nInsert to 2D array at index 2\n', array3)
# insert values to an array before index 2 along axis 0 array4 = np.insert(array1, 2, array2, 0)
print('\nInsert to 2D array at row 2\n', array4)
# insert values to an array before index 2 along axis 1 array5 = np.insert(array1, 2, array2, 1)
print('\nInsert to 2D array at column 2\n', array5)

输出

Insert to 2D array at index 2
[0 1 4 5 2 3]

Insert to 2D array at row 2
 [[0 1]
 [2 3]
 [4 5]]

Insert to 2D array at column 2
[[0 1 4]
 [2 3 5]]

注意: 如果未提供轴,则数组将被展平。


示例 3:在给定索引之前向 2-D 数组插入内容

import numpy as np

array1 = np.array([[0, 1], [2, 3]])
array2 = np.array([4, 5])

# insert elements from array2 before indices 0 and 1 of array1 array3 = np.insert(array1, [0, 1], array2)
print('\nInsert to 2D array before indices 0 and 1\n', array3)
# insert elements from array2 before row 0 and row 1 of array1 along axis 0 array4 = np.insert(array1, [0, 1], array2, axis=0)
print('\nInsert to 2D array before row 0 and row 1 along axis 0\n', array4)
# insert elements from array2 before column 0 and column 1 of array1 along axis 1 array5 = np.insert(array1, [0, 1], array2, axis=1)
print('\nInsert to 2D array before column 0 and column 1 along axis 1\n', array5)

输出

Insert to 2D array before indices 0 and 1
[4 0 5 1 2 3]
Insert to 2D array before row 0 and row 1 along axis 0
 [[4 5]
 [0 1]
 [4 5]
 [2 3]]

Insert to 2D array before column 0 and column 1 along axis 1
[[4 0 5 1]
 [4 2 5 3]]

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战