创建矩阵
array()函数
import numpy as np
a = np.array([[1,2,3],
[2,3,4]])
print(a)
运行结果为:
[[1 2 3]
[2 3 4]]
创建全0矩阵
b = np.zeros((3,4))
print(b)
运行结果为:
[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]
创建全1矩阵
c = np.ones((3,4))
print(c)
运行结果为:
[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]
创建空矩阵
d = np.empty((3,4))
print(d)
运行结果为:
[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]
创建等差矩阵
e = np.arange(10,20,2)
print(e)
运行结果为:
[10 12 14 16 18]
f = np.arange(12).reshape((3,4))
print(f)
运行结果为:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
linspace() 创建线性矩阵
g = np.linspace(1,10,5)
print(g)
运行结果为:
[ 1. 3.25 5.5 7.75 10. ]
创建随机矩阵
# 生成长度为5,在[0,1)之间平均分布的随机矩阵
h = np.random.random(size=5) 或 h = np.random.random((5,))
print(h)
运行结果为:
[0.41531148 0.53401601 0.7455592 0.69346509 0.03288469]
矩阵的算术运算
position-wise(大小相同矩阵)
broadcast(大小相同矩阵)
dot()方法(点积的矩阵乘法)
矩阵的切片和聚合
矩阵的切片操作
矩阵的聚合
还可以使用axis参数指定行和列的聚合:
矩阵的转置和重构
矩阵的转置
矩阵的重构
传入参数时,也可以传入-1,系统会自动判断维度。
import numpy as np
a = np.array([[1,2,3,4,5,6]]).reshape(2,-1)
print(a)
运行结果为:
[[1 2 3]
[4 5 6]]
n维矩阵(ndarray)
很多时候,改变维度只需要在numpy的函数中加一个逗号:
矩阵的合并
上下合并(vertical stack)
import numpy as np
a = np.array([1,2,3])
b = np.array([4,5,6])
print(np.vstack((a,b)))
运行结果为:
[[1 2 3]
[4 5 6]]
左右合并(horizontal stack)
import numpy as np
a = np.array([1,2,3])
b = np.array([4,5,6])
print(np.hstack((a,b)))
运行结果为:
[1 2 3 4 5 6]
将序列变为有维度的矩阵
利用[:,np.newaxis]或[np.newaxis,:]
import numpy as np
a = np.array([1,2,3])
print(a)
a = np.array([1,2,3])[:,np.newaxis]
print(a)
a = np.array([1,2,3])[np.newaxis,:]
print(a)
运行结果为:
[1 2 3]
[[1]
[2]
[3]]
[[1 2 3]]
多个数组的合并(concatenate)
import numpy as np
a = np.array([1,1,1])[:,np.newaxis]
print(a)
b = np.array([2,2,2])[:,np.newaxis]
print(b)
c = np.concatenate((a,b,b,a),axis=1)
print(c)
运行结果为:
[[1]
[1]
[1]]
[[2]
[2]
[2]]
[[1 2 2 1]
[1 2 2 1]
[1 2 2 1]]
矩阵的分割
等份分割(split)
import numpy as np
a = np.arange(12).reshape(3,4)
print(a)
print(np.split(a,2,axis=1))
运行结果为:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[array([[0, 1],
[4, 5],
[8, 9]]), array([[ 2, 3],
[ 6, 7],
[10, 11]])]
不等份分割(array_split)
import numpy as np
a = np.arange(12).reshape(3,4)
print(a)
print(np.array_split(a,3,axis=1))
运行结果为:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[array([[0, 1],
[4, 5],
[8, 9]]), array([[ 2],
[ 6],
[10]]), array([[ 3],
[ 7],
[11]])]
vsplit和hsplit方法
import numpy as np
a = np.arange(12).reshape(3,4)
print(a)
print(np.vsplit(a,3))
print(np.hsplit(a,2))
运行结果为:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[array([[0, 1, 2, 3]]), array([[4, 5, 6, 7]]), array([[ 8, 9, 10, 11]])]
[array([[0, 1],
[4, 5],
[8, 9]]), array([[ 2, 3],
[ 6, 7],
[10, 11]])]
矩阵的复制
a = b(关联地址)
import numpy as np
a = np.arange(4)
print(a)
b = a
b[0] = 100
print(b)
print(a)
运行结果为:
[0 1 2 3]
[100 1 2 3]
[100 1 2 3]
深度复制(只取数据 不关联地址)
采用copy()函数
import numpy as np
a = np.arange(4)
print(a)
b = a.copy()
b[0] = 100
print(b)
print(a)
运行结果为:
[0 1 2 3]
[100 1 2 3]
[0 1 2 3]