一、数组运算
#逐个元素进行运算,即逐个对应元素相加、相减、相乘、相除、比较
import numpy as np
a = np.array([10, 20, 30, 40])
b = np.arange(4)
print(a, b)
c = a-b
d = a+b
e = a*b
f = b**2
g = 10*np.sin(a)
print(c)
print(d)
print(e)
print(f)
print(g)
print(b)
print(b<3)
print(b==3)
=================== RESTART: C:/Users/wyt/Desktop/test.py ===================
[10 20 30 40] [0 1 2 3]
[10 19 28 37]
[10 21 32 43]
[ 0 20 60 120]
[0 1 4 9]
[-5.44021111 9.12945251 -9.88031624 7.4511316 ]
[0 1 2 3]
[ True True True False]
[False False False True]
二、矩阵计算
1.逐个相乘 同数组计算
import numpy as np
a = np.array([[10, 20],
[30, 40]])
b = np.arange(4).reshape((2,2))
print('a=',a)
print('b=',b)
c = a-b
d = a+b
e = a*b
f = b**2
g = 10*np.sin(a)
print('c=',c)
print('d=',d)
print('e=',e)
print('f=',f)
print('g=',g)
print('b=',b)
print(b<3)
print(b==3)
=================== RESTART: C:/Users/wyt/Desktop/test.py ===================
a= [[10 20]
[30 40]]
b= [[0 1]
[2 3]]
c= [[10 19]
[28 37]]
d= [[10 21]
[32 43]]
e= [[ 0 20]
[ 60 120]]
f= [[0 1]
[4 9]]
g= [[-5.44021111 9.12945251]
[-9.88031624 7.4511316 ]]
b= [[0 1]
[2 3]]
[[ True True]
[ True False]]
[[False False]
[False True]]
2.矩阵乘法法则
语法:np.dot(a, b) 或 a.dot(b)
import numpy as np
a = np.array([[10, 20],
[30, 40]])
b = np.arange(4).reshape((2,2))
print('a=',a)
print('b=',b)
c = a* b
c_dot = np.dot(a, b)
c_dot_2 = a.dot(b)
print(c)
print(c_dot)
print(c_dot_2)
=================== RESTART: C:/Users/wyt/Desktop/test.py ===================
a= [[10 20]
[30 40]]
b= [[0 1]
[2 3]]
[[ 0 20]
[ 60 120]]
[[ 40 70]
[ 80 150]]
[[ 40 70]
[ 80 150]]
三、生成随机矩阵、求和、获取最大值、最小值
import numpy as np
a = np.random.random((2,4)) #创建随机2行4列矩阵
b = np.sum(a) #求矩阵a中所有元素的和
c = np.min(a) #求矩阵a中的最小值
d = np.max(a) #求矩阵a中的最大值
e = np.sum(a, axis = 0) #求维度0(每一列)的和
f = np.sum(a, axis = 1) #求维度1(每一行)的和
g = np.min(a, axis = 0) #求维度0(每一列)的最小值
h = np.min(a, axis = 1) #求维度1(每一行)的最小值
i = np.max(a, axis = 0) #求维度0(每一列)的最小值
j = np.max(a, axis = 1) #求维度1(每一行)的最大值
print(a)
print(b)
print(c)
print(d)
print(e)
print(f)
print(g)
print(h)
print(i)
print(j)
=================== RESTART: C:/Users/wyt/Desktop/test.py ===================
[[0.96822865 0.71306605 0.59009166 0.86502946]
[0.49244838 0.47406958 0.62828058 0.27098843]]
5.002202792067487
0.2709884260616199
0.9682286479190232
[1.46067703 1.18713564 1.21837224 1.13601789]
[3.13641583 1.86578696]
[0.49244838 0.47406958 0.59009166 0.27098843]
[0.59009166 0.27098843]
[0.96822865 0.71306605 0.62828058 0.86502946]
[0.96822865 0.62828058]
>>>