Python numpy.insert()
Python numpy.insert()函数沿着提到的axis在给定的索引之前插入值。
语法 :
numpy.insert(array, object, values, axis = None)
参数 :
array : [array_like]输入数组。
object : [int, array of ints]子数组,在其前面插入数值的索引。
values : [array_like]要添加到数组中的值。值的形状应该是arr[…,obj,…] = values。如果values的类型与arr的类型不同,values将被转换为arr的类型。
axis :我们想沿着这个轴插入数值。默认情况下,它的对象是应用于扁平化的数组
返回 :
一个数组的副本,其数值是按照所述对象沿给定轴线插入的。
代码1:从1D数组中删除
# Python Program illustrating
# numpy.insert()
import numpy as geek
#Working on 1D
arr = geek.arange(5)
print("1D arr : \n", arr)
print("Shape : ", arr.shape)
# value = 9
# index = 1
# Insertion before first index
a = geek.insert(arr, 1, 9)
print("\nArray after insertion : ", a)
print("Shape : ", a.shape)
# Working on 2D array
arr = geek.arange(12).reshape(3, 4)
print("\n\n2D arr : \n", arr)
print("Shape : ", arr.shape)
a = geek.insert(arr, 1, 9, axis = 1)
print("\nArray after insertion : \n", a)
print("Shape : ", a.shape)
输出 :
1D arr :
[0 1 2 3 4]
Shape : (5,)
Array after insertion : [0 9 1 2 3 4]
Shape : (6,)
2D arr :
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
Shape : (3, 4)
Array after insertion :
[[ 0 9 1 2 3]
[ 4 9 5 6 7]
[ 8 9 9 10 11]]
Shape : (3, 5)
代码2:处理标量
# Python Program illustrating
# numpy.insert()
import numpy as geek
# Working on 2D array
arr = geek.arange(12).reshape(3, 4)
print("2D arr : \n", arr)
print("Shape : ", arr.shape)
# Working with Scalars
a = geek.insert(arr, [1], [[6],[9],], axis = 0)
print("\nArray after insertion : \n", a)
print("Shape : ", a.shape)
# Working with Scalars
a = geek.insert(arr, [1], [[8],[7],[9]], axis = 1)
print("\nArray after insertion : \n", a)
print("Shape : ", a.shape)
输出 :
2D arr :
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
Shape : (3, 4)
Array after insertion :
[[ 0 1 2 3]
[ 6 6 6 6]
[ 9 9 9 9]
[ 4 5 6 7]
[ 8 9 10 11]]
Shape : (5, 4)
Array after insertion :
[[ 0 8 1 2 3]
[ 4 7 5 6 7]
[ 8 9 9 10 11]]
Shape : (3, 5)
代码3:在不同的点插入
# Python Program illustrating
# numpy.insert()
import numpy as geek
#Working on 1D
arr = geek.arange(6).reshape(2, 3)
print("1D arr : \n", arr)
print("Shape : ", arr.shape)
# value = 9
# index = 1
# Insertion before first index
a = geek.insert(arr, (2, 4), 9)
print("\nInsertion at two points : ", a)
print("Shape : ", a.shape)
# Working on 2D array
arr = geek.arange(12).reshape(3, 4)
print("\n\n2D arr : \n", arr)
print("Shape : ", arr.shape)
a = geek.insert(arr, (0, 3), 66, axis = 1)
print("\nInsertion at two points : \n", a)
print("Shape : ", a.shape)
输出 :
1D arr :
[[0 1 2]
[3 4 5]]
Shape : (2, 3)
Insertion at two points : [0 1 9 2 3 9 4 5]
Shape : (8,)
2D arr :
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
Shape : (3, 4)
Insertion at two points :
[[66 0 1 2 66 3]
[66 4 5 6 66 7]
[66 8 9 10 66 11]]
Shape : (3, 6)