numpy官网
0.numpy的基本属性
import numpy as np
#0.numpy的属性:长宽,size,维度
array = np.array([[1, 3, 5],
[2, 4, 6]])
print(array)
print('number of dim:', array.ndim)
print('shape:', array.shape)
print('size:', array.size)
1.矩阵的创建
import numpy as np
a = np.array([2, 3, 4, 5], dtype=np.int)
b = np.array([2.1, 3.2, 4.3, 5.4], dtype=np.float)
print(a)
print(a.dtype)
print(b)
print(b.dtype)
print(b.ndim)
c = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int)
print(c)
print(c.ndim)
#1.1创建全0/1矩阵
d = np.zeros((3, 4))
print(d)
e = np.ones((4, 5), dtype=np.int)
print(e)
#1.2 arange创建矩阵,设置步长为1
f = np.arange(1, 21, 1).reshape(4, 5)
print(f)
g = np.arange(12).reshape(3, 4)
print(g)
#1.3 linspace创建矩阵,平均分段
h = np.linspace(10, 20, 6).reshape(2, 3)
print(h)
#1.4 random创建随机矩阵
i = np.random.random((2,4))
print(i)
2.numpy基础运算
#2.0矩阵四则运算
import numpy as np
a = np.arange(1, 12, 2).reshape(2, 3)
b = np.arange(1, 7, 1).reshape(2, 3)
c = a + b
d = b - a
e = a * b
f = a / b
g = a ** b
h = a % b
print(a)
print(b)
print(c)
print(d)
print(e)
print(f)
print(g)
print(h)
#2.1 三角函数计算:sin cos tan
i = 10*np.sin(a)
j = 10*np.cos(a)
k = 10*np.tan(a)
print(i)
print(j)
print(k)
#2.2 比较运算
print(a < 5)
print(a == 5)
#2.3 矩阵乘法
a = np.array([[1, 2],
[3, 4]])
b = np.arange(4).reshape(2,2)
print(a)
print(b)
e = a * b
e_dot = np.dot(a, b)
e_dot1 = a.dot(b)
print(e)
print(e_dot)
print(e_dot1)
矩阵相乘最重要的方法是一般矩阵乘积。它只有在第一个矩阵的列数(column)和第二个矩阵的行数(row)相同时才有意义
矩阵相乘
#2.4 矩阵运算
import numpy as np
f = np.random.random((3,4))
print(f)
#每一行中的最大/最小值
print(np.max(f, axis=1))
print(np.min(f, axis=1))
#每一列中的最大/最小值
print(np.max(f, axis=0))
print(np.min(f, axis=0))
#每一行的平均值
print(np.mean(f, axis=1))
print(np.average(f, axis=1))
#每一列的平均值
print(np.mean(f, axis=0))
print(np.average(f, axis=0))
#每一行的中值
print(np.median(f, axis=1))
#每一列的中值
print(np.median(f, axis=0))
#每一行的和
print(np.sum(f, axis=1))
#每一列的和
print(np.sum(f, axis=0))
#累加
print(np.cumsum(f))
#差值
print(np.diff(f))
#最大值的索引
print(np.argmax(f))
#最小值的索引
print(np.argmin(f))
#逐行进行排序
print(np.sort(f))
#矩阵转置
print(np.transpose(f))
#滤波
print(np.clip(f, 0.4, 0.6))
3.numpy索引
import numpy as np
A = np.arange(3, 15)
print(A)
print(A[3])
B = np.arange(3,15).reshape((3, 4))
print(B)
#第3行的所有值
print(B[2])
#第3行第2列的值
print(B[2][1])
#第3列的所有值
print(B[:, 2])
#迭代每一行
for row in B:
print(row)
#迭代每一列
for column in np.transpose(B):
print(column)
#迭代每一项
print(B.flatten())
for i in B.flat:
print(i)
4.矩阵合并
import numpy as np
A = np.array([1, 1, 1])
B = np.array([2, 2, 2])
C1 = np.vstack((A, B))
C2 = np.hstack((A, B))
print(C1)
print(C1.shape)
print(C2)
print(C2.shape)
5.矩阵分割
import numpy as np
A = np.arange(1, 13).reshape(3, 4)
print(A)
#两种方式纵向分割
print(np.hsplit(A, 2))
print(np.split(A, 2, axis=1))
#两种方式横向分割
print(np.vsplit(A, 3))
print(np.split(A, 3, axis=0))
#另一种分割方式
print(np.array_split(A, 4, axis=0))
6.numpy的copy和deep copy
import numpy as np
A = np.arange(12).reshape(3,4)
print(A)
B = A
C = A.copy() #deep copy
print(B is A)
print(C is A)
A[2] = 10
A[2, 2] = 20
print(B is A)
print(B)
print(C)
网友评论