04.数组与矩阵运算
生成数组
>>> import numpy as np >>> np.random.randn(10) array([ 0.52712347, -1.65888503, -1.00390235, 1.01367036, -0.15752943, -2.2986508 , -0.00966312, -0.70276299, 1.03832744, -0.56927384]) >>> np.random.randint(10,size=20).reshape(2,10) array([[1, 9, 3, 4, 2, 8, 7, 2, 0, 4], [5, 0, 5, 7, 5, 3, 2, 6, 8, 3]]) >>> a = np.random.randint(10,size=20).reshape(4,5) >>> b = np.random.randint(10,size=20).reshape(4,5) >>> a,b (array([[4, 3, 0, 6, 0], [1, 5, 1, 3, 3], [0, 9, 8, 4, 9], [4, 9, 5, 5, 2]]), array([[6, 5, 6, 8, 4], [0, 7, 4, 9, 9], [9, 8, 9, 1, 7], [1, 3, 7, 3, 7]]))
数组加减乘除
>>> a+b array([[10, 8, 6, 14, 4], [ 1, 12, 5, 12, 12], [ 9, 17, 17, 5, 16], [ 5, 12, 12, 8, 9]]) >>> a*b array([[24, 15, 0, 48, 0], [ 0, 35, 4, 27, 27], [ 0, 72, 72, 4, 63], [ 4, 27, 35, 15, 14]]) >>> a/b <stdin>:1: RuntimeWarning: divide by zero encountered in true_divide array([[0.66666667, 0.6 , 0. , 0.75 , 0. ], [ inf, 0.71428571, 0.25 , 0.33333333, 0.33333333], [0. , 1.125 , 0.88888889, 4. , 1.28571429], [4. , 3. , 0.71428571, 1.66666667, 0.28571429]])
矩阵预运算
>>> np.mat([[1,2,3],[4,5,6]]) matrix([[1, 2, 3], [4, 5, 6]]) >>> A = np.mat(a) >>> B = np.mat(b) >>> A-B matrix([[-2, -2, -6, -2, -4], [ 1, -2, -3, -6, -6], [-9, 1, -1, 3, 2], [ 3, 6, -2, 2, -5]]) >>> A*B Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Users\Mr_wa\anaconda3\lib\site-packages\numpy\matrixlib\defmatrix.py", line 220, in __mul__ return N.dot(self, asmatrix(other)) File "<__array_function__ internals>", line 5, in dot ValueError: shapes (4,5) and (4,5) not aligned: 5 (dim 1) != 4 (dim 0)
注:矩阵运算法则要求前者的列数=后者的行数
>>> b = np.random.randint(10,size=20).reshape(5,4)
>>> B = np.mat(b)
>>> B
matrix([[5, 2, 8, 5],
[5, 5, 6, 9],
[6, 9, 2, 4],
[8, 6, 2, 2],
[0, 7, 9, 5]])
>>> A*B
matrix([[ 83, 59, 62, 59],
[ 60, 75, 73, 75],
[125, 204, 159, 166],
[135, 142, 124, 141]])
其他
>>> np.unique(a) array([0, 1, 2, 3, 4, 5, 6, 8, 9]) >>> sum(a) array([ 9, 26, 14, 18, 14]) >>> sum(a[0]) 13 >>> sum(a[:,0] ... ) 9 >>> a.max() 9 >>> max(a[0]) 6