numpy使用2
numpy插入
参数说明
第一个 插入对象
第二个 values 插入值
第三个 axis=0是按行插入 =1是按列插入
第四个 obj 插入在什么位置
import numpy as np
test1 = np.array([[1,2,3]])
test2 = np.array([4,5,6])
y = np.insert(test1,values=test2,axis=0,obj=1)#往shape为(1,3)的矩阵上第1行插入1行
print(y)
输出结果:
[[1 2 3]
[4 5 6]]
import numpy as np
test1 = np.array([[1,2,3],[1,2,3]])
test2 = np.array([[9,9],[9,9]])
y = np.insert(test1,values=test2,axis=1,obj=1)
#往shape为(2,3)的矩阵在在索引为1列上多加两列,即多添加一个(2,2)矩阵
print(y)
输出结果:
[[1 9 9 2 3]
[1 9 9 2 3]]
注意 将一个矩阵插入另一个矩阵中 当按行还是按列插时,一定要想明白这个插入进去的矩阵是否满足被插的维度要求,否则会报错
例如:
import numpy as np
test1 = np.array([[1,2,3],[1,2,3]])
test2 = np.array([[9,9],[9,9]])
y = np.insert(test1,values=test2,axis=0,obj=0)
print(y)
会报错 试图将(2,2)矩阵放在(2,3)矩阵原来的第0行上,肯定报错
import numpy as np
test = np.array([[1,2,3]])
print(np.insert(test,obj=0,values=1,axis=0))#自动在第0行多加一行1
结果:
[[1 1 1]
[1 2 3]]
numpy合并
import numpy as np
#矩阵实现按行合并
test1 = np.array([[1,2,3],[4,5,6]])
test2 = np.array([[7,8,9],[10,11,12]])
test3 = np.append(test1,test2,axis=0)
print(test3)
结果:
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]
#矩阵实现按列合并
test1 = np.array([[1,2,3],[4,5,6]])
test2 = np.array([[7,8,9],[10,11,12]])
test3 = np.append(test1,test2,axis=1)
print(test3)
结果:
[[ 1 2 3 7 8 9]
[ 4 5 6 10 11 12]]