1. ndarray广播机制的两条规则
-
规则一:为缺失的维度补维度
-
规则二:缺失的元素用已有值填充
# 导包
import numpy as np
# 例1
m = np.ones((2,3),dtype=np.int8)
a = np.arange(3)
display(m,a)
# 执行结果
array([[1, 1, 1],
[1, 1, 1]], dtype=int8)
array([0, 1, 2])
"""
对a数组缺失的维度进行补充,使用已有的值进行填充,最后进行相加
[[0, 1, 2],
[0, 1, 2]]
"""
m + a
# 执行结果
array([[1, 2, 3],
[1, 2, 3]])
# 例2
a = np.arange(3).reshape((3,1))
b = np.arange(3)
display(a,b)
# 执行结果
array([[0],
[1],
[2]])
array([0, 1, 2])
"""
自动扩充填补:
[[0,0,0],
[1,1,1],
[2,2,2]]
[[0,1,2],
[0,1,2],
[0,1,2]]
"""
a+b
# 执行结果
array([[0, 1, 2],
[1, 2, 3],
[2, 3, 4]])
# 习题
a = np.ones((4,1),dtype=np.int8)
b = np.arange(4)
display(a,b)
# 执行结果
array([[1],
[1],
[1],
[1]], dtype=int8)
array([0, 1, 2, 3])
a + b
# 执行结果
array([[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4]])
2.其他常见数学操作
-
定义数组
n = np.array([1,4,8,9,16,25,64])
n
# 执行结果
array([ 1, 4, 8, 9, 16, 25, 64])
-
abs
# 绝对值
np.abs(n)
# 执行结果
array([ 1, 4, 8, 9, 16, 25, 64])
-
sqrt
# 平方根
np.sqrt(n)
# n ** 0.5
# 执行结果
array([1. , 2. , 2.82842712, 3. , 4. ,
5. , 8. ])
-
square
# 平方
np.square(n)
# n ** 2
# 执行结果
array([ 1, 16, 64, 81, 256, 625, 4096])
-
exp
# 指数e
np.exp(n)
# 执行结果
array([2.71828183e+00, 5.45981500e+01, 2.98095799e+03, 8.10308393e+03,
8.88611052e+06, 7.20048993e+10, 6.23514908e+27])
-
log
# 自然对数:以e为底的对数,ln3
np.log(n)
# 执行结果
array([0. , 1.38629436, 2.07944154, 2.19722458, 2.77258872,
3.21887582, 4.15888308])
np.log(np.e)
# 执行结果
1.0
np.e
# 执行结果
2.718281828459045
np.log(1)
# 执行结果
0.0
# 2为底的对数
np.log2(n)
# 执行结果
array([0. , 2. , 3. , 3.169925 , 4. ,
4.64385619, 6. ])
# 10为底的对数,常用对数
np.log10(n)
# 执行结果
array([0. , 0.60205999, 0.90308999, 0.95424251, 1.20411998,
1.39794001, 1.80617997])
-
sin
# 正弦
np.sin(n)
# 执行结果
array([ 0.84147098, -0.7568025 , 0.98935825, 0.41211849, -0.28790332,
-0.13235175, 0.92002604])
-
cos
# 余弦
np.cos(n)
# 执行结果
array([ 0.54030231, -0.65364362, -0.14550003, -0.91113026, -0.95765948,
0.99120281, 0.39185723])
-
tan
# 正切
np.tan(n)
# 执行结果
array([ 1.55740772, 1.15782128, -6.79971146, -0.45231566, 0.30063224,
-0.13352641, 2.34786031])
-
round
# 四舍五入np.round(n,2)
# 执行结果
array([ 1, 4, 8, 9, 16, 25, 64])
-
ceil
# 向上取整
np.ceil(n)
array([ 1., 4., 8., 9., 16., 25., 64.])
-
floor
# 向下取整
np.floor(n)
# 执行结果
array([ 1., 4., 8., 9., 16., 25., 64.])
-
cumsum
# 累加
np.cumsum(n)
array([ 1, 5, 13, 22, 38, 63, 127])