import numpy as np
x = np.arange(10) # 生成数据
np.sin(x) # 对矩阵x中每个元素取正弦
np.cos(x) # 对矩阵x中每个元素取余弦
np.tan(x) # 对矩阵x中每个元素取正切
np.arcsin(x) # 对矩阵x中每个元素取反正弦
np.arccos(x) # 对矩阵x中每个元素取反余弦
np.arctan(x) # 对矩阵x中每个元素取反正切
np.exp(x) # 对矩阵x中每个元素取指数函数
np.sqrt(x) # 对矩阵x中每个元素取开方
# 元素级乘法,对应元素相乘 * 或 np.multiply()
m = np.array([[1,2,3],[4,5,6]])
n = np.array([[1,2,3],[4,5,6]])
m * n
# array([[ 1, 4, 9],
# [16, 25, 36]])
np.multiply(m, n)
# array([[ 1, 4, 9],
# [16, 25, 36]])
###############################
# 矩阵乘积 np.matmul()
m = np.array([[1,2,3],[4,5,6]])
n = np.array([[1,2],[3,4],[5,6]])
m.shape # (2, 3)
n.shape # (3, 2)
np.matmul(m, n) # (2, 2)
#array([[22, 28],
# [49, 64]])
###############################
# np.dot()
# 如果处理的是一维数组,则得到的是两数组的內积
# 如果是二维数组(矩阵)之间的运算,则得到的是矩阵积
m = np.array([1,2,3])
n = np.array([4,5,6])
np.dot(m, n) # 1*4 + 2*5 + 3*6 = 32
a = np.array([[1,2,3],[4,5,6]])
b = np.array([[1,2],[3,4],[5,6]])
np.dot(a, b)
# array([[22, 28],
# [49, 64]])
m = np.array([[1,2,3],[4,5,6]])
m.transpose() # np.transpose(m)
# array([[1, 4],
# [2, 5],
# [3, 6]])
m.T
# array([[1, 4],
# [2, 5],
# [3, 6]])
m = np.array([[1, 2], [3, 4]])
np.linalg.inv(m)
# array([[-2. , 1. ],
# [ 1.5, -0.5]])
# 转换为matrix对象
M = np.matrix(m)
M.I
# matrix([[-2. , 1. ],
# [ 1.5, -0.5]])
m = np.array([[1,2,3],[4,5,6]])
m.max() # 6
m.min() # 1
# 使用axis关键字,获取行或列的最大、最小值
m.max(axis=0)
# array([4, 5, 6])
m = np.array([[1,2,3],[4,5,6]])
m.mean() # 3.5
np.average(m) # 3.5
m.mean(axis=0) # 行平均,array([2.5, 3.5, 4.5])
m = np.array([[1,2,3],[4,5,6]])
m.var() # 2.9166666666666665
m.var(axis=0) # array([2.25, 2.25, 2.25])
m.std() # 1.707825127659933
m.std(axis=0) # array([1.5, 1.5, 1.5])
m = np.array([[1,2,3],[4,5,6]])
np.median(m) # 3.5
np.median(m,axis=0) # array([2.5, 3.5, 4.5])
m = np.array([[1,2,3],[4,5,6]])
m.sum() # 21
m.sum(axis=0) # array([5, 7, 9])
m.cumsum() # array([ 1, 3, 6, 10, 15, 21], dtype=int32)
m.cumsum(axis=0)
# array([[1, 2, 3],
# [5, 7, 9]], dtype=int32)
m.cumsum(axis=1)
# array([[ 1, 3, 6],
# [ 4, 9, 15]], dtype=int32)
m = np.array([[1,2,3],[4,5,6],[7,8,9]])
m[0:1] # 第一行数据 array([[1, 2, 3]])
m[1, 1:2] # 第二行,第二列数据 array([5])
m[2, :] # 第三行数据 array([[7, 8, 9]])
m = np.array([[1,2,3],[4,5,6],[7,8,9]])
m[m>5]
# array([6, 7, 8, 9])
#将矩阵中大于6的元素变成0
m[m>5] = 0
m
# array([[1, 2, 3],
# [4, 5, 0],
# [0, 0, 0]])
# 返回值:所有小于min的值都等于min,所有大于max的值都等于max
m = np.array([[1,2,3],[4,5,6],[7,8,9]])
m.clip(3,6)
# array([[3, 3, 3],
# [4, 5, 6],
# [6, 6, 6]])
m = np.array([[1,2,3],[1,2,3]])
n = np.array([[4,5,6],[4,5,6]])
np.hstack([m,n]) # 水平合并
# array([[1, 2, 3, 4, 5, 6],
# [1, 2, 3, 4, 5, 6]])
np.vstack([m,n]) # 垂直合并
# array([[1, 2, 3],
# [1, 2, 3],
# [4, 5, 6],
# [4, 5, 6]])
np.concatenate((m,n), axis=0)
# array([[1, 2, 3],
# [1, 2, 3],
# [4, 5, 6],
# [4, 5, 6]])
np.concatenate((m,n), axis=1)
# array([[1, 2, 3, 4, 5, 6],
# [1, 2, 3, 4, 5, 6]])
参考:
https://www.cnblogs.com/qflyue/p/8244331.html
https://www.numpy.org.cn/user/setting-up.html