#快速创建数组
import numpy as np
np.random.randn(10) #快速创建10个元素的一元数组
np.random.randint(10) #随机生成10以内的整型数据
np.random.randint(10,size=10) #快速随机生成10以内的整型10个元素的一元数组
np.random.randint(10,size=(3,4)) #快速随机生成10以内的整型三行四列数组
np.random.randint(10,size=20).reshape(4,5) #或者使用reshape函数重塑多维数组
#数组运算
a = np.random.randint(10,size=20).reshape(4,5)
b = np.random.randint(10,size=20).reshape(4,5)
a
输出:
array([[8, 3, 6, 5, 7],
[2, 5, 0, 1, 7],
[7, 2, 5, 8, 9],
[5, 3, 2, 6, 1]])
b
输出:
array([[8, 9, 1, 9, 3],
[1, 8, 2, 6, 2],
[0, 9, 4, 8, 6],
[1, 6, 8, 1, 3]])
a + b
输出:
array([[16, 12, 7, 14, 10],
[ 3, 13, 2, 7, 9],
[ 7, 11, 9, 16, 15],
[ 6, 9, 10, 7, 4]])
a - b
输出:
array([[ 0, -6, 5, -4, 4],
[ 1, -3, -2, -5, 5],
[ 7, -7, 1, 0, 3],
[ 4, -3, -6, 5, -2]])
a * b
输出:
array([[64, 27, 6, 45, 21],
[ 2, 40, 0, 6, 14],
[ 0, 18, 20, 64, 54],
[ 5, 18, 16, 6, 3]])
a / b
输出:
<ipython-input-21-d8e10abd5ab6>:1: RuntimeWarning: divide by zero encountered in true_divide
a / b
array([[1. , 0.33333333, 6. , 0.55555556, 2.33333333],
[2. , 0.625 , 0. , 0.16666667, 3.5 ],
[ inf, 0.22222222, 1.25 , 1. , 1.5 ],
[5. , 0.5 , 0.25 , 6. , 0.33333333]])
#会提示warning,做除时有非法的0,最后结果中会有inf无穷大
#总结:数组的 "+", "-", "*", “/"都是对应位置的加减乘除
#矩阵的创建和运算
np.mat([[1,2,3],[4,5,6]])
输出:
matrix([[1, 2, 3],
[4, 5, 6]])
#数组也可转换成矩阵,比如数组a,
np.mat(a)
输出:
matrix([[8, 3, 6, 5, 7],
[2, 5, 0, 1, 7],
[7, 2, 5, 8, 9],
[5, 3, 2, 6, 1]])
#矩阵运算
A = np.mat(a)
B = np.mat(b)
B
输出:
matrix([[8, 9, 1, 9, 3],
[1, 8, 2, 6, 2],
[0, 9, 4, 8, 6],
[1, 6, 8, 1, 3]])
A + B
输出:
matrix([[16, 12, 7, 14, 10],
[ 3, 13, 2, 7, 9],
[ 7, 11, 9, 16, 15],
[ 6, 9, 10, 7, 4]])
A - B
输出:
matrix([[ 0, -6, 5, -4, 4],
[ 1, -3, -2, -5, 5],
[ 7, -7, 1, 0, 3],
[ 4, -3, -6, 5, -2]])
#小结:矩阵的加减和数组的加减一样,都是对应位置的加减
A * B
输出:
ValueError: shapes (4,5) and (4,5) not aligned: 5 (dim 1) != 4 (dim 0)
#报错,提示A的列数和B的行数不一致导致
#重新生成A和B
A = np.mat(np.random.randint(10,size=20).reshape(4,5))
B = np.mat(np.random.randint(10,size=20).reshape(5,4))
A
matrix([[4, 4, 9, 8, 6],
[1, 8, 9, 4, 5],
[6, 3, 3, 4, 5],
[2, 5, 6, 1, 9]])
B
matrix([[5, 3, 4, 6],
[0, 9, 1, 4],
[8, 9, 5, 9],
[0, 3, 9, 1],
[7, 6, 5, 9]])
A * B
matrix([[134, 189, 167, 183],
[112, 198, 118, 168],
[ 89, 114, 103, 124],
[121, 162, 97, 168]])