1.逻辑函数
numpy.all(a, axis=None, out=None, keepdims=np._NoValue) 测试沿给定轴的所有数组元素是否都为 True。
numpy.any(a, axis=None, out=None, keepdims=np._NoValue) 测试沿给定轴的任一数组元素是否为 True。
numpy.isnan(x, *args, **kwargs) 对每个元素进行 NaN 测试,并以布尔数组的形式返回结果。
逻辑运算
numpy.logical_not
numpy.logical_and
numpy.logical_or
numpy.logical_xor
numpy.logical_not(x, *args, **kwargs)计算非x元素的真值
numpy.logical_and(x1, x2, *args, **kwargs) 计算x1 和 x2的真值。
numpy.logical_or(x1, x2, *args, **kwargs) 计算 x1 或 x2 的真值。
numpy.logical_xor(x1, x2, *args, **kwargs) 逐元素计算 x1 XOR x2 的逻辑值。
numpy.greater(x1, x2, *args, **kwargs) 元素级返回 (x1 > x2) 的布尔值。
numpy.greater_equal(x1, x2, *args, **kwargs) 元素级返回 (x1 >= x2) 的布尔值。
numpy.equal(x1, x2, *args, **kwargs) 元素级返回 (x1 == x2) 的布尔值。
numpy.not_equal(x1, x2, *args, **kwargs) 元素级返回 (x1 != x2) 的布尔值。
numpy.less(x1, x2, *args, **kwargs) 元素级返回 (x1 < x2) 的布尔值。
numpy.less_equal(x1, x2, *args, **kwargs) 元素级返回 (x1 <= x2) 的布尔值。
numpy.isclose(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False) 返回一个布尔数组,表示两个数组在给定容差范围内元素逐一相等。
numpy.allclose(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False) 如果两个数组在给定容差范围内元素逐一相等,则返回 True。
numpy.allclose() 等价于 numpy.all(isclose(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan))
判断是否为True的计算依据:
np.absolute(a - b) <= (atol + rtol * absolute(b))
- atol:float,绝对公差。
- rtol:float,相对公差。
代码:
import numpy as np
# numpy.all 和 numpy.any
a = np.array([0, 4, 5])
b = np.copy(a)
print(np.all(a == b)) # True
print(np.any(a == b)) # True
b[0] = 1
print(np.all(a == b)) # False
print(np.any(a == b)) # True
print(np.all([1.0, np.nan])) # True
print(np.any([1.0, np.nan])) # True
a = np.eye(3)
print(np.all(a, axis=0)) # [False False False]
print(np.any(a, axis=0)) # [ True True True]
# numpy.isnan
a=np.array([1,2,np.nan])
print(np.isnan(a))
#[False False True]
# numpy.logical_not
print(np.logical_not(3))
# False
print(np.logical_not([True, False, 0, 1]))
# [False True True False]
x = np.arange(5)
print(np.logical_not(x < 3))
# [False False False True True]
# numpy.logical_and
print(np.logical_and(True, False))
# False
print(np.logical_and([True, False], [True, False]))
# [ True False]
print(np.logical_and(x > 1, x < 4))
# [False False True True False]
# numpy.logical_or
print(np.logical_or(True, False))
# True
print(np.logical_or([True, False], [False, False]))
# [ True False]
print(np.logical_or(x < 1, x > 3))
# [ True False False False True]
# numpy.logical_xor
print(np.logical_xor(True, False))
# True
print(np.logical_xor([True, True, False, False], [True, False, True, False]))
# [False True True False]
print(np.logical_xor(x < 1, x > 3))
# [ True False False False True]
print(np.logical_xor(0, np.eye(2)))
# [[ True False]
# [False True]]
# 逻辑对比
x = np.array([1, 2, 3, 4, 5, 6, 7, 8])
y = x > 2
print(y)
print(np.greater(x, 2))
# [False False True True True True True True]
y = x >= 2
print(y)
print(np.greater_equal(x, 2))
# [False True True True True True True True]
y = x == 2
print(y)
print(np.equal(x, 2))
# [False True False False False False False False]
y = x != 2
print(y)
print(np.not_equal(x, 2))
# [ True False True True True True True True]
y = x < 2
print(y)
print(np.less(x, 2))
# [ True False False False False False False False]
y = x <= 2
print(y)
print(np.less_equal(x, 2))
# [ True True False False False False False False]
x = np.array([[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25],
[26, 27, 28, 29, 30],
[31, 32, 33, 34, 35]])
y = x > 20
print(y)
print(np.greater(x, 20))
# [[False False False False False]
# [False False False False False]
# [ True True True True True]
# [ True True True True True]
# [ True True True True True]]
y = x >= 20
print(y)
print(np.greater_equal(x, 20))
# [[False False False False False]
# [False False False False True]
# [ True True True True True]
# [ True True True True True]
# [ True True True True True]]
y = x == 20
print(y)
print(np.equal(x, 20))
# [[False False False False False]
# [False False False False True]
# [False False False False False]
# [False False False False False]
# [False False False False False]]
y = x != 20
print(y)
print(np.not_equal(x, 20))
# [[ True True True True True]
# [ True True True True False]
# [ True True True True True]
# [ True True True True True]
# [ True True True True True]]
y = x < 20
print(y)
print(np.less(x, 20))
# [[ True True True True True]
# [ True True True True False]
# [False False False False False]
# [False False False False False]
# [False False False False False]]
y = x <= 20
print(y)
print(np.less_equal(x, 20))
# [[ True True True True True]
# [ True True True True True]
# [False False False False False]
# [False False False False False]
# [False False False False False]]
x = np.array([[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25],
[26, 27, 28, 29, 30],
[31, 32, 33, 34, 35]])
np.random.seed(20200611)
y = np.random.randint(10, 50, 5)
print(y)
# [32 37 30 24 10]
z = x > y
print(z)
print(np.greater(x, y))
# [[False False False False True]
# [False False False False True]
# [False False False False True]
# [False False False True True]
# [False False True True True]]
z = x >= y
print(z)
print(np.greater_equal(x, y))
# [[False False False False True]
# [False False False False True]
# [False False False True True]
# [False False False True True]
# [False False True True True]]
z = x == y
print(z)
print(np.equal(x, y))
# [[False False False False False]
# [False False False False False]
# [False False False True False]
# [False False False False False]
# [False False False False False]]
z = x != y
print(z)
print(np.not_equal(x, y))
# [[ True True True True True]
# [ True True True True True]
# [ True True True False True]
# [ True True True True True]
# [ True True True True True]]
z = x < y
print(z)
print(np.less(x, y))
# [[ True True True True False]
# [ True True True True False]
# [ True True True False False]
# [ True True True False False]
# [ True True False False False]]
z = x <= y
print(z)
print(np.less_equal(x, y))
# [[ True True True True False]
# [ True True True True False]
# [ True True True True False]
# [ True True True False False]
# [ True True False False False]]
x = np.isclose([1e10, 1e-7], [1.00001e10, 1e-8])
print(x) # [ True False]
x = np.allclose([1e10, 1e-7], [1.00001e10, 1e-8])
print(x) # False
x = np.isclose([1e10, 1e-8], [1.00001e10, 1e-9])
print(x) # [ True True]
x = np.allclose([1e10, 1e-8], [1.00001e10, 1e-9])
print(x) # True
x = np.isclose([1e10, 1e-8], [1.0001e10, 1e-9])
print(x) # [False True]
x = np.allclose([1e10, 1e-8], [1.0001e10, 1e-9])
print(x) # False
x = np.isclose([1.0, np.nan], [1.0, np.nan])
print(x) # [ True False]
x = np.allclose([1.0, np.nan], [1.0, np.nan])
print(x) # False
x = np.isclose([1.0, np.nan], [1.0, np.nan], equal_nan=True)
print(x) # [ True True]
x = np.allclose([1.0, np.nan], [1.0, np.nan], equal_nan=True)
print(x) # True
2.数学函数
1.向量化和广播
向量化和广播这两个概念是 numpy 内部实现的基础。有了向量化,编写代码时无需使用显式循环。这些循环实际上不能省略,只不过是在内部实现,被代码中的其他结构代替。向量化的应用使得代码更简洁,可读性更强,也可以说使用了向量化方法的代码看上去更“Pythonic”。
广播(Broadcasting)机制描述了 numpy 如何在算术运算期间处理具有不同形状的数组,让较小的数组在较大的数组上“广播”,以便它们具有兼容的形状。并不是所有的维度都要彼此兼容才符合广播机制的要求,但它们必须满足一定的条件。
若两个数组的各维度兼容,也就是两个数组的每一维等长,或其中一个数组为 一维,那么广播机制就适用。如果这两个条件不满足,numpy就会抛出异常,说两个数组不兼容。
总结来说,广播的规则有三个:
如果两个数组的维度数dim不相同,那么小维度数组的形状将会在左边补1。
如果shape维度不匹配,但是有维度是1,那么可以扩展维度是1的维度匹配另一个数组;
如果shape维度不匹配,但是没有任何一个维度是1,则匹配引发错误;
算数运算
numpy.add
numpy.subtract
numpy.multiply
numpy.divide
numpy.floor_divide
numpy.power
numpy.add(x1, x2, *args, **kwargs) 对参数进行逐元素相加。
numpy.subtract(x1, x2, *args, **kwargs) 对参数进行逐元素相减。
numpy.multiply(x1, x2, *args, **kwargs) 对参数进行逐元素相乘。
numpy.divide(x1, x2, *args, **kwargs) 返回输入的真实除法结果,逐元素。
numpy.floor_divide(x1, x2, *args, **kwargs) 返回小于或等于输入除法结果的最大整数。
numpy.power(x1, x2, *args, **kwargs) 第一个数组的元素按第二个数组的元素为指数进行逐元素幂运算。
numpy.sqrt
numpy.square
numpy.sqrt(x, *args, **kwargs) 返回数组的非负平方根,逐元素计算。
numpy.square(x, *args, **kwargs) 返回输入的逐元素平方。
三角函数¶
numpy.sin
numpy.cos
numpy.tan
numpy.arcsin
numpy.arccos
numpy.arctan
numpy.sin(x, *args, **kwargs) 三角正弦函数,逐元素计算。
numpy.cos(x, *args, **kwargs) 逐元素余弦。
numpy.tan(x, *args, **kwargs) 逐元素计算正切。
numpy.arcsin(x, *args, **kwargs) 逐元素反正弦。
numpy.arccos(x, *args, **kwargs) 三角反余弦函数,逐元素计算。
numpy.arctan(x, *args, **kwargs) 三角反正切函数,逐元素计算。
通用函数(universal function)通常叫作ufunc,它对数组中的各个元素逐一进行操作。这表明,通用函数分别处理输入数组的每个元素,生成的结果组成一个新的输出数组。输出数组的大小跟输入数组相同。
三角函数等很多数学运算符合通用函数的定义,例如,计算平方根的sqrt()函数、用来取对数的log()函数和求正弦值的sin()函数
指数和对数
numpy.exp
numpy.log
numpy.exp2
numpy.log2
numpy.log10
numpy.exp(x, *args, **kwargs) 计算输入数组中所有元素的指数。
numpy.log(x, *args, **kwargs) 自然对数,逐元素计算。
numpy.exp2(x, *args, **kwargs) 计算输入数组中所有元素的2的幂。
numpy.log2(x, *args, **kwargs) 计算x的以2为底的对数。
numpy.log10(x, *args, **kwargs) 返回输入数组的以10为底的对数,逐元素计算。
加法函数、乘法函数
numpy.sum(a[, axis=None, dtype=None, out=None, …]) 对指定轴上的数组元素求和。
numpy.cumsum(a, axis=None, dtype=None, out=None) 返回指定轴上元素的累积和。
numpy.prod(a[, axis=None, dtype=None, out=None, …]) 返回数组元素在指定轴上的乘积。
numpy.cumprod(a, axis=None, dtype=None, out=None) 返回沿指定轴的元素累积乘积。
numpy.diff 差值
numpy.diff(a, n=1, axis=-1, prepend=np._NoValue, append=np._NoValue) 沿给定轴计算第 n 个离散差分。
a:输入矩阵
n:可选,代表要执行几次差值
axis:默认是最后一个
四舍五入
numpy.around 舍入
numpy.around(a, decimals=0, out=None) 将数字均匀地四舍五入到指定的小数位数。
numpy.ceil(x, *args, **kwargs) 返回输入元素的上限。
numpy.floor(x, *args, **kwargs) 返回输入元素的下限。
杂项
numpy.clip(a, a_min, a_max, out=None, **kwargs):限制数组中的值(裁剪)。
给定一个区间,区间外的值将被裁剪到区间边缘。例如,如果指定了区间 [0, 1],小于 0 的值将变为 0,大于 1 的值将变为 1。
numpy.absolute(x, *args, **kwargs) 逐元素计算绝对值。
numpy.abs(x, *args, **kwargs) 是该函数的简写。
numpy.sign(x, *args, **kwargs) 返回数字的逐元素符号指示。
import numpy as np
# 1.array()函数创建数组
def array(p_object, dtype=None, copy=True, order='K', subok=False, ndmin=0):
pass
# 创建一维数组
a = np.array([0, 1, 2, 3, 4])
b = np.array((0, 1, 2, 3, 4))
print(a, type(a))
# [0 1 2 3 4] <class 'numpy.ndarray'>
print(b, type(b))
# [0 1 2 3 4] <class 'numpy.ndarray'>
# 创建二维数组
c = np.array([[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25],
[26, 27, 28, 29, 30],
[31, 32, 33, 34, 35]])
print(c, type(c))
# [[11 12 13 14 15]
# [16 17 18 19 20]
# [21 22 23 24 25]
# [26 27 28 29 30]
# [31 32 33 34 35]] <class 'numpy.ndarray'>
# 创建三维数组
d = np.array([[(1.5, 2, 3), (4, 5, 6)],
[(3, 2, 1), (4, 5, 6)]])
print(d, type(d))
# [[[1.5 2. 3. ]
# [4. 5. 6. ]]
#
# [[3. 2. 1. ]
# [4. 5. 6. ]]] <class 'numpy.ndarray'>
# 2.通过asarray()函数创建数组
# asarray()和array()的用法是一样的
# array()和asarray()都可以将结构数据转化为 ndarray
def asarray(a, dtype=None, order=None):
return array(a, dtype, copy=False, order=order)
x = [[1, 1, 1], [1, 1, 1], [1, 1, 1]]
y = np.array(x)
z = np.asarray(x)
x[1][2] = 2
print(x,type(x))
# [[1, 1, 1], [1, 1, 2], [1, 1, 1]] <class 'list'>
print(y,type(y))
# [[1 1 1]
# [1 1 1]
# [1 1 1]] <class 'numpy.ndarray'>
print(z,type(z))
# [[1 1 1]
# [1 1 1]
# [1 1 1]] <class 'numpy.ndarray'>
# array()和asarray()的区别。
# (array()和asarray()主要区别就是当数据源是ndarray 时,array()仍然会 copy 出一个副本,占用新的内存,但不改变 dtype 时 asarray()不会。)
x = np.array([[1, 1, 1], [1, 1, 1], [1, 1, 1]])
y = np.array(x)
z = np.asarray(x)
# w = np.asarray(x, dtype=np.int)
x[1][2] = 2
print(x,type(x),x.dtype)
# [[1 1 1]
# [1 1 2]
# [1 1 1]] <class 'numpy.ndarray'> int32
print(y,type(y),y.dtype)
# [[1 1 1]
# [1 1 1]
# [1 1 1]] <class 'numpy.ndarray'> int32
print(z,type(z),z.dtype)
# [[1 1 1]
# [1 1 2]
# [1 1 1]] <class 'numpy.ndarray'> int32
print(w,type(w),w.dtype)
# [[1 1 1]
# [1 1 2]
# [1 1 1]] <class 'numpy.ndarray'> int32
# 通过fromfunction()函数进行创建
def fromfunction(function, shape, **kwargs):
pass
# 例:通过在每个坐标上执行一个函数来构造数组
def f(x, y):
return 10 * x + y
x = np.fromfunction(f, (5, 4), dtype=int)
print(x)
# [[ 0 1 2 3]
# [10 11 12 13]
# [20 21 22 23]
# [30 31 32 33]
# [40 41 42 43]]
x = np.fromfunction(lambda i, j: i == j, (3, 3), dtype=int)
print(x)
# [[ True False False]
# [False True False]
# [False False True]]
x = np.fromfunction(lambda i, j: i + j, (3, 3), dtype=int)
print(x)
# [[0 1 2]
# [1 2 3]
# [2 3 4]]
# 依据 ones 和 zeros 填充方式
# 零数组
def zeros(shape, dtype=None, order='C'):
pass
def zeros_like(a, dtype=None, order='K', subok=True, shape=None):
pass
x = np.zeros(5)
print(x) # [0. 0. 0. 0. 0.]
x = np.zeros([2, 3])
print(x)
# [[0. 0. 0.]
# [0. 0. 0.]]
x = np.array([[1, 2, 3], [4, 5, 6]])
y = np.zeros_like(x)
print(y)
# [[0 0 0]
# [0 0 0]]
# 一数组
def ones(shape, dtype=None, order='C'):
pass
def ones_like(a, dtype=None, order='K', subok=True, shape=None):
pass
x = np.ones(5)
print(x) # [1. 1. 1. 1. 1.]
x = np.ones([2, 3])
print(x)
# [[1. 1. 1.]
# [1. 1. 1.]]
x = np.array([[1, 2, 3], [4, 5, 6]])
y = np.ones_like(x)
print(y)
# [[1 1 1]
# [1 1 1]]
# 空数组
def empty(shape, dtype=None, order='C'):
pass
def empty_like(prototype, dtype=None, order='K', subok=True, shape=None):
pass
x = np.empty(5)
print(x)
# [1.95821574e-306 1.60219035e-306 1.37961506e-306
# 9.34609790e-307 1.24610383e-306]
x = np.empty((3, 2))
print(x)
# [[1.60220393e-306 9.34587382e-307]
# [8.45599367e-307 7.56598449e-307]
# [1.33509389e-306 3.59412896e-317]]
x = np.array([[1, 2, 3], [4, 5, 6]])
y = np.empty_like(x)
print(y)
# [[ 7209029 6422625 6619244]
# [ 100 707539280 504]]
# 单位数组
def eye(N, M=None, k=0, dtype=float, order='C'):
pass
def identity(n, dtype=None):
pass
x = np.eye(4)
print(x)
# [[1. 0. 0. 0.]
# [0. 1. 0. 0.]
# [0. 0. 1. 0.]
# [0. 0. 0. 1.]]
x = np.eye(2, 3)
print(x)
# [[1. 0. 0.]
# [0. 1. 0.]]
x = np.identity(4)
print(x)
# [[1. 0. 0. 0.]
# [0. 1. 0. 0.]
# [0. 0. 1. 0.]
# [0. 0. 0. 1.]]
# 对角数组
def diag(v, k=0):
pass
x = np.arange(9).reshape((3, 3)) # 生成一个到9为止,不包9的3*3数组
print(x)
# [[0 1 2]
# [3 4 5]
# [6 7 8]]
print(np.diag(x)) # [0 4 8]
print(np.diag(x, k=1)) # [1 5]
print(np.diag(x, k=-1)) # [3 7]
v = [1, 3, 5, 7]
x = np.diag(v)
print(x)
# [[1 0 0 0]
# [0 3 0 0]
# [0 0 5 0]
# [0 0 0 7]]
# 常数数组
def full(shape, fill_value, dtype=None, order='C'):
pass
def full_like(a, fill_value, dtype=None, order='K', subok=True, shape=None):
pass
x = np.full((2,), 7)
print(x)
# [7 7]
x = np.full(2, 7)
print(x)
# [7 7]
x = np.full((2, 7), 7)
print(x)
# [[7 7 7 7 7 7 7]
# [7 7 7 7 7 7 7]]
x = np.array([[1, 2, 3], [4, 5, 6]])
y = np.full_like(x, 7)
print(y)
# [[7 7 7]
# [7 7 7]]
# 利用数值范围来创建ndarray
x = np.arange(5)
print(x) # [0 1 2 3 4]
x = np.arange(3, 7, 2)
print(x) # [3 5]
x = np.linspace(start=0, stop=2, num=9)
print(x)
# [0. 0.25 0.5 0.75 1. 1.25 1.5 1.75 2. ]
x = np.logspace(0, 1, 5)
print(np.around(x, 2))
# [ 1. 1.78 3.16 5.62 10. ]
#np.around 返回四舍五入后的值,可指定精度。
# around(a, decimals=0, out=None)
# a 输入数组
# decimals 要舍入的小数位数。 默认值为0。 如果为负,整数将四舍五入到小数点左侧的位置
x = np.linspace(start=0, stop=1, num=5)
x = [10 ** i for i in x]
print(np.around(x, 2))
# [ 1. 1.78 3.16 5.62 10. ]
x = np.random.random(5)
print(x)
# [0.41768753 0.16315577 0.80167915 0.99690199 0.11812291]
x = np.random.random([2, 3])
print(x)
# [[0.41151858 0.93785153 0.57031309]
# [0.13482333 0.20583516 0.45429181]]
# 结构数组的创建
# 1.利用字典来定义结构
personType = np.dtype({
'names': ['name', 'age', 'weight'],
'formats': ['U30', 'i8', 'f8']})
a = np.array([('Liming', 24, 63.9), ('Mike', 15, 67.), ('Jan', 34, 45.8)],
dtype=personType)
print(a, type(a))
# [('Liming', 24, 63.9) ('Mike', 15, 67. ) ('Jan', 34, 45.8)]
# <class 'numpy.ndarray'>
# 2.利用包含多个元组的列表来定义结构
personType = np.dtype([('name', 'U30'), ('age', 'i8'), ('weight', 'f8')])
a = np.array([('Liming', 24, 63.9), ('Mike', 15, 67.), ('Jan', 34, 45.8)],
dtype=personType)
print(a, type(a))
# [('Liming', 24, 63.9) ('Mike', 15, 67. ) ('Jan', 34, 45.8)]
# <class 'numpy.ndarray'>
# 结构数组的取值方式和一般数组差不多,可以通过下标取得元素:
print(a[0])
# ('Liming', 24, 63.9)
print(a[-2:])
# [('Mike', 15, 67. ) ('Jan', 34, 45.8)]
# 我们可以使用字段名作为下标获取对应的值
print(a['name'])
# ['Liming' 'Mike' 'Jan']
print(a['age'])
# [24 15 34]
print(a['weight'])
# [63.9 67. 45.8]
# 数组的类型
a = np.array([1, 2, 3, 4, 5])
print(a.shape) # (5,)
print(a.dtype) # int32
print(a.size) # 5
print(a.ndim) # 1
print(a.itemsize) # 4
b = np.array([[1, 2, 3], [4, 5, 6.0]])
print(b.shape) # (2, 3)
print(b.dtype) # float64
print(b.size) # 6
print(b.ndim) # 2
print(b.itemsize) # 8
# 在ndarray中所有元素必须是同一类型,否则会自动向下转换,int->float->str。
a = np.array([1, 2, 3, 4, 5])
print(a) # [1 2 3 4 5]
b = np.array([1, 2, 3, 4, '5'])
print(b) # ['1' '2' '3' '4' '5']
c = np.array([1, 2, 3, 4, 5.0])
print(c) # [1. 2. 3. 4. 5.]
# 三角函数
x = np.linspace(start=0, stop=np.pi / 2, num=10)
print(x)
# [0. 0.17453293 0.34906585 0.52359878 0.6981317 0.87266463
# 1.04719755 1.22173048 1.3962634 1.57079633]
y = np.sin(x)
print(y)
# [0. 0.17364818 0.34202014 0.5 0.64278761 0.76604444
# 0.8660254 0.93969262 0.98480775 1. ]
z = np.arcsin(y)
print(z)
# [0. 0.17453293 0.34906585 0.52359878 0.6981317 0.87266463
# 1.04719755 1.22173048 1.3962634 1.57079633]
y = np.cos(x)
print(y)
# [1.00000000e+00 9.84807753e-01 9.39692621e-01 8.66025404e-01
# 7.66044443e-01 6.42787610e-01 5.00000000e-01 3.42020143e-01
# 1.73648178e-01 6.12323400e-17]
z = np.arccos(y)
print(z)
# [0. 0.17453293 0.34906585 0.52359878 0.6981317 0.87266463
# 1.04719755 1.22173048 1.3962634 1.57079633]
y = np.tan(x)
print(y)
# [0.00000000e+00 1.76326981e-01 3.63970234e-01 5.77350269e-01
# 8.39099631e-01 1.19175359e+00 1.73205081e+00 2.74747742e+00
# 5.67128182e+00 1.63312394e+16]
z = np.arctan(y)
print(z)
# [0. 0.17453293 0.34906585 0.52359878 0.6981317 0.87266463
# 1.04719755 1.22173048 1.3962634 1.57079633]
# 指数对数函数
x = np.arange(1, 5)
print(x)
# [1 2 3 4]
y = np.exp(x)
print(y)
# [ 2.71828183 7.3890561 20.08553692 54.59815003]
z = np.log(y)
print(z)
# [1. 2. 3. 4.]
#累加,累积
x = np.array([[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25],
[26, 27, 28, 29, 30],
[31, 32, 33, 34, 35]])
y = np.sum(x)
print(y) # 575
y = np.sum(x, axis=0)
print(y) # [105 110 115 120 125]
y = np.sum(x, axis=1)
print(y) # [ 65 90 115 140 165]
x = np.array([[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25],
[26, 27, 28, 29, 30],
[31, 32, 33, 34, 35]])
y = np.cumsum(x)
print(y)
# [ 11 23 36 50 65 81 98 116 135 155 176 198 221 245 270 296 323 351
# 380 410 441 473 506 540 575]
y = np.cumsum(x, axis=0)
print(y)
# [[ 11 12 13 14 15]
# [ 27 29 31 33 35]
# [ 48 51 54 57 60]
# [ 74 78 82 86 90]
# [105 110 115 120 125]]
y = np.cumsum(x, axis=1)
print(y)
# [[ 11 23 36 50 65]
# [ 16 33 51 70 90]
# [ 21 43 66 90 115]
# [ 26 53 81 110 140]
# [ 31 63 96 130 165]]
print("------------")
x = np.array([[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25],
[26, 27, 28, 29, 30],
[31, 32, 33, 34, 35]])
y = np.prod(x)
print(y) # 788529152
y = np.prod(x, axis=0)
print(y)
# [2978976 3877632 4972968 6294624 7875000]
y = np.prod(x, axis=1)
print(y)
# [ 360360 1860480 6375600 17100720 38955840]
x = np.array([[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25],
[26, 27, 28, 29, 30],
[31, 32, 33, 34, 35]])
y = np.cumprod(x)
print(y)
# [ 11 132 1716 24024 360360 5765760
# 98017920 1764322560 -837609728 427674624 391232512 17180672
# 395155456 893796352 870072320 1147043840 905412608 -418250752
# 755630080 1194065920 -1638662144 -897581056 444596224 -2063597568
# 788529152]
y = np.cumprod(x, axis=0)
print(y)
# [[ 11 12 13 14 15]
# [ 176 204 234 266 300]
# [ 3696 4488 5382 6384 7500]
# [ 96096 121176 150696 185136 225000]
# [2978976 3877632 4972968 6294624 7875000]]
y = np.cumprod(x, axis=1)
print(y)
# [[ 11 132 1716 24024 360360]
# [ 16 272 4896 93024 1860480]
# [ 21 462 10626 255024 6375600]
# [ 26 702 19656 570024 17100720]
# [ 31 992 32736 1113024 38955840]]
# 差值
A = np.arange(2, 14).reshape((3, 4))
A[1, 1] = 8
print(A)
# [[ 2 3 4 5]
# [ 6 8 8 9]
# [10 11 12 13]]
print(np.diff(A))
# [[1 1 1]
# [2 0 1]
# [1 1 1]]
print(np.diff(A, axis=0))
# [[4 5 4 4]
# [4 3 4 4]]
# 四舍五入
x = np.random.rand(3, 3) * 10
print(x)
# [[6.59144457 3.78566113 8.15321227]
# [1.68241475 3.78753332 7.68886328]
# [2.84255822 9.58106727 7.86678037]]
y = np.around(x)
print(y)
# [[ 7. 4. 8.]
# [ 2. 4. 8.]
# [ 3. 10. 8.]]
y = np.around(x, decimals=2)
print(y)
# [[6.59 3.79 8.15]
# [1.68 3.79 7.69]
# [2.84 9.58 7.87]]
# 上限下限
x = np.random.rand(3, 3) * 10
print(x)
# [[0.67847795 1.33073923 4.53920122]
# [7.55724676 5.88854047 2.65502046]
# [8.67640444 8.80110812 5.97528726]]
y = np.ceil(x)
print(y)
# [[1. 2. 5.]
# [8. 6. 3.]
# [9. 9. 6.]]
y = np.floor(x)
print(y)
# [[0. 1. 4.]
# [7. 5. 2.]
# [8. 8. 5.]]
# 杂项
# 裁剪
x = np.array([[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25],
[26, 27, 28, 29, 30],
[31, 32, 33, 34, 35]])
y = np.clip(x, a_min=20, a_max=30)
print(y)
# [[20 20 20 20 20]
# [20 20 20 20 20]
# [21 22 23 24 25]
# [26 27 28 29 30]
# [30 30 30 30 30]]
# 绝对值
x = np.arange(-5, 5)
print(x)
# [-5 -4 -3 -2 -1 0 1 2 3 4]
y = np.abs(x)
print(y)
# [5 4 3 2 1 0 1 2 3 4]
y = np.absolute(x)
print(y)
# [5 4 3 2 1 0 1 2 3 4]
# 逐元素符号指示
x = np.arange(-5, 5)
print(x)
#[-5 -4 -3 -2 -1 0 1 2 3 4]
print(np.sign(x))
#[-1 -1 -1 -1 -1 0 1 1 1 1]
练习:
import numpy as np
# 将数组a中大于30的值替换为30,小于10的值替换为10。
np.set_printoptions(precision=2)
a = np.random.uniform(1, 50, (4,5))
print(a)
# [[11.03 16.29 10.8 31.74 27.91]
# [26.54 14.91 23.65 44.54 6.62]
# [29.18 32.79 24.59 7.24 32.19]
# [13.58 11.98 10.42 1.46 1.9 ]]
y = np.clip(a, a_min=10, a_max=30)
print(y)
# [[11.03 16.29 10.8 30. 27.91]
# [26.54 14.91 23.65 30. 10. ]
# [29.18 30. 24.59 10. 30. ]
# [13.58 11.98 10.42 10. 10. ]]
# 找到一个一维数字数组a中的所有峰值。峰顶是两边被较小数值包围的点。
a = np.array([1, 3, 7, 1, 2, 6, 0, 1])
b1 = np.diff(a)
b2 = np.sign(b1)
b3 = np.diff(b2)
print(b1) # [ 2 4 -6 1 4 -6 1]
print(b2) # [ 1 1 -1 1 1 -1 1]
print(b3) # [ 0 -2 2 0 -2 2]
index = np.where(np.equal(b3, -2))[0] + 1
print(index) # [2 5]
# 对于给定的一维数组,计算窗口大小为3的移动平均值。
np.random.seed(100)
z = np.random.randint(10, size=10)
print(z)
# [8 8 3 7 7 0 4 2 5 2]
def MovingAverage(arr, n=3):
a = np.cumsum(arr)
a[n:] = a[n:] - a[:-n]
return a[n - 1:] / n
r = MovingAverage(z, 3)
print(np.around(r, 2))
# [6.33 6. 5.67 4.67 3.67 2. 3.67 3. ]
# 对一个5x5的随机矩阵做归一化
A = np.random.random((5,5))
Amax,Amin = A.max(),A.min()
A = (A - Amin) / (Amax - Amin)
# 用五种不同的方法去提取一个随机数组的整数部分
Z = np.random.uniform(0,10,10)
print(Z - Z%1)
print(np.floor(Z))
print (np.ceil(Z)-1)
print (Z.astype(int))
print (np.trunc(Z))
# 考虑一维数组Z,构建一个二维数组,其第一行为(Z [0],Z [1],Z [2]),随后的每一行都移位1(最后一行应为(Z [ -3],Z [-2],Z [-1])
# 通过改内存地址来实现
np.arange(10).itemsize
from numpy.lib import stride_tricks
def rolling(a, window):
shape = (a.size - window + 1, window)
strides = (a.itemsize, a.itemsize)
return stride_tricks.as_strided(a, shape=shape, strides=strides)
Z = rolling(np.arange(10), 3)
print (Z)
# 考虑两组点集P0和P1去描述一组线(二维)和一个点p,如何计算点p到每一条线 i (P0[i],P1[i])的距离?
def distance(P0,P1,p):
A = -1/(P1[:,0]-P0[:,0])
B = -1/(P1[:,1]-P0[:,1])
C = P0[:,0]/(P1[:,0]-P0[:,0])-P0[:,1]/(P1[:,1]-P0[:,1])
return np.abs(A*p[:,0]+B*p[:,1]+C)/np.sqrt(A**2+B**2)
P0 = np.random.uniform(-10, 10, [10,2])
P1 = np.random.uniform(-10, 10, [10,2])
p = np.random.uniform(-10, 10, [1,2])
print(distance(P0,P1,p))
# 画正弦函数和余弦函数, x = np.arange(0, 3 * np.pi, 0.1)?
from matplotlib import pyplot as plt
x = np.arange(0, 3*np.pi, 0.1)
y1 = np.sin(x)
y2 = np.cos(x)
plt.plot(x, y1)
plt.plot(x, y2)
# 减去矩阵每一行的平均值 ?
X = np.random.rand(5, 10)
# 新
Y = X - X.mean(axis=1, keepdims=True)
# 旧
Y = X - X.mean(axis=1).reshape(-1, 1)
print(Y)
# 进行概率统计分析 ?
arr1 = np.random.randint(1,10,10)
arr2 = np.random.randint(1,10,10)
print("arr1的平均数为:%s" %np.mean(arr1))
print("arr1的中位数为:%s" %np.median(arr1))
print("arr1的方差为:%s" %np.var(arr1))
print("arr1的标准差为:%s" %np.std(arr1))
print("arr1,arr的相关性矩阵为:%s" %np.cov(arr1,arr2))
print("arr1,arr的协方差矩阵为:%s" %np.corrcoef(arr1,arr2))
# 如何得到两个数组元素匹配的位置?
a = np.array([1, 2, 3, 2, 3, 4, 3, 4, 5, 6])
b = np.array([7, 2, 10, 2, 7, 4, 9, 4, 9, 8])
mask = np.equal(a, b)
# 方法1
x = np.where(mask)
print(x) # (array([1, 3, 5, 7], dtype=int64),)
# 方法2
x = np.nonzero(mask)
print(x) # (array([1, 3, 5, 7], dtype=int64),)
# 筛选5-10中是所有数
a = np.array([2, 6, 1, 9, 10, 3, 27])
mask = np.logical_and(np.greater_equal(a,5),np.less_equal(a,10))
x = np.where(mask)
print(a[x])
# 方法2
x = np.logical_and(a >=5 , a <=10)
print(x)
# 对于两个随机数组A和B,检查他们是否相等
A = np.random.randint(0,2,5)
B = np.random.randint(0,2,5)
equal = np.all(A == B)
print(equal)
# False
# 何对布尔值取反,或者原位(in-place)改变浮点数的符号(sign)?
Z = np.array([0,1])
np.logical_not(Z, out=Z) # out:将结果返回到指定数组
print(Z)
Z = np.array([0.2,1.15]) # 取负数
print(Z)
np.negative(Z, out=Z)
# 找出数组中与给定值最接近的数
# 1. 创建二维数组 Z
Z = np.array([[0,1,2,3],[4,5,6,7]])
print(Z) # 输出二维数组的原始值
# 2. 定义目标值 z
z = 5.1
# 3. 核心计算:找到与z最接近的元素的一维索引
min_index = np.abs(Z - z).argmin()
# 4. 通过一维索引获取对应的元素值
print(Z.flat[min_index])
490

被折叠的 条评论
为什么被折叠?



