NumPy简明教程
一、初识NumPy
(一)什么是NumPy
1、基本概念
NumPy是Python中科学计算的基础包。它是一个Python库,提供多维数组对象,各种派生对象(如掩码数组和矩阵),以及用于数组快速操作的各种API,有包括数学、逻辑、形状操作、排序、选择、输入输出、离散傅立叶变换、基本线性代数,基本统计运算和随机模拟等等。
NumPy包的核心是 ndarray 对象。它封装了python原生的同数据类型的 n 维数组,为了保证其性能优良,其中有许多操作都是代码在本地进行编译后执行的。
2、为什么NumPy这么快
NumPy的两个特征,是NumPy的大部分功能的基础:矢量化和广播
矢量化描述了代码中没有任何显式的循环,索引等 - 这些当然是预编译的C代码中幕后优化的结果。矢量化代码有许多优点,其中包括:
- 矢量化代码更简洁,更易于阅读
- 更少的代码行通常意味着更少的错误
- 代码更接近于标准的数学符号(通常,更容易正确编码数学结构)
- 矢量化产生更多
Pythonic代码。如果没有矢量化,我们的代码就会被低效且难以阅读的for循环所困扰。
广播是用于描述操作的隐式逐元素行为的术语; 一般来说,在NumPy中,所有操作,不仅仅是算术运算,而是逻辑,位,功能等,都以这种隐式的逐元素方式表现,即它们进行广播。
(二)实例演示
下面给出两个例子进行说明:
- 实例一
将一维数组中的每个元素与相同长度的另一个序列中的相应元素相乘的情况。如果数据存储在两个Python 列表 a 和 b 中,我们可以迭代每个元素,如下所示:
a = [1, 2, 3]
b = [4, 5, 6]
c = []
for i in range(len(a)):
c.append(a[i] * b[i])
print(c)
"""
[4, 10, 18]
"""
确实符合我们的要求,但如果a和b每一个都包含数以百万计的数字,我们会付出Python中循环的效率低下的代价。
如果我们借助于NumPy来完成:
a = np.array(a)
b = np.array(b)
c = a * b
print(c)
"""
[ 4 10 18]
"""
- 实例二
将多多维数组中的元素都加1,如果使用Python的基本语法:
l1 = [[1,2,3],[4,5,6],[7,8,9]]
for i, l in enumerate(l1):
for j, v in enumerate(l):
l1[i][j] += 1
print(l1)
"""
[[2, 3, 4], [5, 6, 7], [8, 9, 10]]
"""
嵌套多层循环,一旦数据量较大,造成效率低下,使用NumPy实现:
import numpy as np
arr = np.array([i for i in range(1, 10)]).reshape(3, 3)
# 法一
arr1 = arr + 1
print(arr1)
# 法二
arr2 = arr + np.ones((3, 3), dtype='int32')
print(arr2)
通过NumPy使代码更加易读以及效率更高。
二、数组
(一)数据类型
NumPy的核心是数组,数组中的每一个元素都有自己的数据类型,在NumPy中的数据类型有如下的种类:
| Numpy 的类型 | C 的类型 | 描述 |
|---|---|---|
| np.int8 | int8_t | 字节(-128到127) |
| np.int16 | int16_t | 整数(-32768至32767) |
| np.int32 | int32_t | 整数(-2147483648至2147483647) |
| np.int64 | int64_t | 整数(-9223372036854775808至9223372036854775807) |
| np.uint8 | uint8_t | 无符号整数(0到255) |
| np.uint16 | uint16_t | 无符号整数(0到65535) |
| np.uint32 | uint32_t | 无符号整数(0到4294967295) |
| np.uint64 | uint64_t | 无符号整数(0到18446744073709551615) |
| np.intp | intptr_t | 用于索引的整数,通常与索引相同 ssize_t |
| np.uintp | uintptr_t | 整数大到足以容纳指针 |
| np.float32 | float | |
| np.float64 / np.float_ | double | 请注意,这与内置python float的精度相匹配。 |
| np.complex64 | float complex | 复数,由两个32位浮点数(实数和虚数组件)表示 |
| np.complex128 / np.complex_ | double complex | 请注意,这与内置python 复合体的精度相匹配。 |
1、dtype的使用
NumPy数值类型是dtype(数据类型)对象的实例,每个对象都具有独特的特征。
数据类型可以用作将python数转换为数组标量的函数,将python数字序列转换为该类型的数组,或作为许多numpy函数或方法接受的dtype关键字的参数。
比如:
>>> import numpy as np
>>> x = np.float32(1.0)
>>> x
1.0
>>> y = np.int_([1,2,4])
>>> y
array([1, 2, 4])
>>> z = np.arange(3, dtype=np.uint8)
>>> z
array([0, 1, 2], dtype=uint8)
要确定数组的类型,查看dtype属性:
>>> z.dtype
dtype('uint8')
2、astype的使用
要转换数组的类型,使用 .astype() 方法或类型本身作为函数。例如:
>>> z.astype(float)
array([ 0., 1., 2.])
>>> np.int8(z)
array([0, 1, 2], dtype=int8)
(二)创建数组
- 将Python可迭代对象转成NumPy数组
- NumPy原生数组的创建
1、将Python可迭代对象转成NumPy数组
通常,在Python中排列成array-like结构的数值数据可以通过使用array()函数转换为数组。最明显的例子是列表和元组。
>>> import numpy as np
>>> x = np.array([2,3,1,0]) # 一维数组
>>> x = np.array([2, 3, 1, 0])
>>> x = np.array([[ 1.+0.j, 2.+0.j], [ 0.+0.j, 0.+0.j], [ 1.+1.j, 3.+0.j]]) # 多维数组
>>> np.array([['a','b',1],[1,2,3]])
array([['a', 'b', '1'],
['1', '2', '3']], dtype='<U1') # 多维混合数据类型数组
>>> x = np.array((2,3,1,0))
>>> x
array([2, 3, 1, 0])
对于dtype='<U1'
其中,第一个字符是字节序,< 表示小端,> 表示大端,| 表示平台的字节序;U是上表中的最后一行Unicode的意思;1代表长度字符串的长度。
2、NumPy原生数组的创建
Numpy内置了创建数组的函数:
- np.zeros、np.ones、np.empty
- np.arrange
- np.random
- np.linespace
2.1 np.zeros、np.ones、np.empty
指定大小的全0或全1数组,值得注意的是:
- 第一个参数是元组,用来指定大小,如(4,5)
- empty不是总是返回全0,有时返回的是未初始的随机值
#创建一维数组
>>> import numpy as np
>>> np.zeros(5,dtype=float)
array([0., 0., 0., 0., 0.]) #创建浮点型全为0的数组
>>> np.zeros(5,dtype=int)
array([0, 0, 0, 0, 0]) #创建整型全为0的数组
>>> np.ones(5)
array([1., 1., 1., 1., 1.]) #创建值全为1的数组
#创建一个空数组,然后将空数组使用fill方法进行填充
>>> a = np.empty(4)
>>> a
array([7.33483560e-315, 7.33405037e-315, 2.49174182e-316, 2.07211804e-316])
>>> a.fill(6)
>>> a
array([6., 6., 6., 6.])
>>>
#创建多维数组
>>> np.zeros((4,5))
>>> np.ones((4,5))
>>> np.empty((3,4))
array([[1.186e-321, 0.000e+000, 0.000e+000, 0.000e+000],
[0.000e+000, 0.000e+000, 0.000e+000, 0.000e+000],
[0.000e+000, 0.000e+000, 0.000e+000, 0.000e+000]])
>>> np.empty((3,4),int) #指定数据类型
array([[1484587258, 0, 1484587600, 0],
[1484428320, 0, 13996488, 0],
[ 7077996, 4784128, 84, 5006336]])
2.2 np.arrange
创建具有有规律递增值的数组。
#创建一维数组
>>> np.arange(10)
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> np.arange(2, 10, dtype=np.float) # 指定数据类型
array([ 2., 3., 4., 5., 6., 7., 8., 9.])
>>> np.arange(2, 3, 0.1) # 步长
array([ 2. , 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9])
#创建多维数组
>>> np.arange(10).reshape(2,5)
array([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]])
2.3 np.random
np.random模块用于创建随机数组的函数 ,内部也有很多创建不同形式的数组函数:
-
np.random.randn(d0, d1, ..., dn) 生成一个(d0, d1, ..., dn)维的数组,服从标准正态分布(均值为0、方差为1)的随机样本数组
-
np.random.rand(d0, d1, ..., dn) 生成一个(d0, d1, ..., dn)维的数组,数组的元素取自[0, 1)上的均分布,若没有参数输入,则生成一个数
-
np.random.randint(low, high=None, size=None, dtype=None) 生成size个整数,取值区间为[low, high),若没有输入参数high则取值区间为[0, low)
-
np.random.random(size=None) 在半开放区间[0.0,1.0)中返回随机浮点数
#一维数组
>>> np.random.randn(5)
array([ 0.80726684, -0.47856828, -1.01387413, -1.81198436, -0.30367494])
#多维数组
>>> np.random.randn(5,4)
array([[ 0.44795214, 0.58889219, 0.6557998 , -0.98750982],
[ 0.96874065, -0.83364282, 0.40935755, 0.17958365],
[-0.3830435 , -0.13996465, 0.65810287, -1.09443092],
[-1.67776307, 0.00275889, -1.32662109, 1.25585212],
[-0.66629589, -1.09667777, 1.08017396, 1.04579035]])
#一个数
>>> np.random.rand()
0.5602091565863412
#多维数组
>>> np.random.rand(2,3)
array([[0.21425158, 0.55603564, 0.71230788],
[0.91407327, 0.12856442, 0.31680005]])
>>> np.random.rand(2,2,3)
array([[[0.66192283, 0.06463257, 0.49716463],
[0.90722766, 0.02891533, 0.97793578]],
[[0.30110233, 0.61075461, 0.85996915],
[0.62196878, 0.82921807, 0.12312781]]])
>>> np.random.randint(6)
4
>>> np.random.randint(6,size=2)
array([1, 5])
>>> np.random.randint(6,size=2,dtype='int64')
array([5, 0], dtype=int64)
>>> np.random.random()
0.45467454915616023
>>>
>>> np.random.random(6)
array([0.30329601, 0.59093303, 0.37975647, 0.23568354, 0.01647539,
0.46731369])
>>> np.random.random((6,3))
array([[8.65067985e-01, 6.32889091e-02, 8.97145125e-01],
[2.41960732e-01, 7.63990918e-01, 3.28925883e-01],
[7.77391602e-01, 2.94343398e-01, 2.47273732e-02],
[6.80504494e-01, 7.56751159e-01, 4.94071081e-04],
[5.18076628e-01, 1.17604372e-01, 3.18197217e-01],
[5.13292960e-01, 5.19054712e-01, 6.87742571e-01]])
2.4 np.linespace
linspace() 将创建具有指定数量元素的数组,并在指定的开始值和结束值之间平均间隔。例如:
>>> np.linspace(1., 4., 6)
array([ 1. , 1.6, 2.2, 2.8, 3.4, 4. ])
np.linspace(1., 4., 6),即从1到4闭区间,划分为6个数据点
间隔就是 (4-1)/ 5 = 0.6
(三)数组操作
1、索引、切片和迭代
一维的数组可以进行索引、切片和迭代操作的,就像 列表 和其他Python序列类型一样:
>>> a = np.arange(10)**3
>>> a
array([ 0, 1, 8, 27, 64, 125, 216, 343, 512, 729])
>>> a[2]
8
>>> a[2:5]
array([ 8, 27, 64])
>>> a[:6:2] = -1000 # equivalent to a[0:6:2] = -1000; from start to position 6, exclusive, set every 2nd element to -1000
>>> a
array([-1000, 1, -1000, 27, -1000, 125, 216, 343, 512, 729])
>>> a[ : :-1] # reversed a
array([ 729, 512, 343, 216, 125, -1000, 27, -1000, 1, -1000])
>>> for i in a:
... print(i**(1/3.))
...
nan
1.0
nan
3.0
nan
5.0
6.0
7.0
8.0
9.0
多维的数组每个轴可以有一个索引。这些索引以逗号分隔的元组给出:
>>> def f(x,y):
... return 10*x+y
...
>>> b = np.fromfunction(f,(5,4),dtype=int)
>>> b
array([[ 0, 1, 2, 3],
[10, 11, 12, 13],
[20, 21, 22, 23],
[30, 31, 32, 33],
[40, 41, 42, 43]])
>>> b[2,3]
23
>>> b[0:5, 1] # each row in the second column of b
array([ 1, 11, 21, 31, 41])
>>> b[ : ,1] # equivalent to the previous example
array([ 1, 11, 21, 31, 41])
>>> b[1:3, : ] # each column in the second and third row of b
array([[10, 11, 12, 13],
[20, 21, 22, 23]])
if
shapewere(2, 2), then the parameters would bearray([[0, 0], [1, 1]])andarray([[0, 1], [0, 1]])
shapewere (5,4)then
xwere[[0 0 0 0] [1 1 1 1] [2 2 2 2] [3 3 3 3] [4 4 4 4]]then
ywere[[0 1 2 3] [0 1 2 3] [0 1 2 3] [0 1 2 3] [0 1 2 3]]
对多维数组进行 迭代(Iterating) 是相对于第一个轴完成的:
>>> for row in b:
... print(row)
...
[0 1 2 3]
[10 11 12 13]
[20 21 22 23]
[30 31 32 33]
[40 41 42 43]
但是,如果想要对数组中的每个元素执行操作,可以使用flat属性,该属性是数组的所有元素的迭代器:
>>> for element in b.flat:
... print(element)
...
0
1
2
3
10
11
12
13
20
21
22
23
30
31
32
33
40
41
42
43
2、通用函数
NumPy提供了一些通用函数,用于处理数组,作用于每一个数组元素:
- 浮动函数
- 统计函数
- 条件函数
- 文件存储函数
2.1 浮动函数
- ceil, 向上最接近的整数
- floor, 向下最接近的整数
- rint, 四舍五入
- isnan, 判断元素是否为 NaN(Not a Number)
- multiply,元素相乘
- divide, 元素相除
>>> arr = np.random.randn(2,3)
>>> arr
array([[ 0.13900355, 1.0035698 , -1.18212763],
[ 0.61880961, 0.55586212, 0.56438219]])
#向上最接近的整数
>>> np.ceil(arr)
array([[ 1., 2., -1.],
[ 1., 1., 1.]])
#向下最接近的整数
>>> np.floor(arr)
array([[ 0., 1., -2.],
[ 0., 0., 0.]])
#四舍五入
>>> np.rint(arr)
array([[ 0., 1., -1.],
[ 1., 1., 1.]])
#判断元素是否为 NaN(Not a Number)
>>> np.isnan(arr)
array([[False, False, False],
[False, False, False]])
>>>
#数组相乘
>>> arr1 = np.random.randn(2,3)
>>> arr1
array([[-0.04220886, 0.86937388, -2.46986511],
[ 1.33986535, -0.70081799, 0.571598 ]])
>>> arr2 = np.multiply(arr,arr1)
>>> arr2
array([[-0.00586718, 0.87247737, 2.91969579],
[ 0.82912156, -0.38955817, 0.32259973]])
#数组相除
>>> arr3 = np.divide(arr,arr1)
>>> arr3
array([[-3.29323126, 1.15435928, 0.47862032],
[ 0.46184462, -0.79316188, 0.98737608]])
>>>
2.2 统计函数
- np.mean(x [, axis]): 所有元素的平均值,参数是 number 或 ndarray
- np.sum(x [, axis]): 所有元素的和,参数是 number 或 ndarray
- np.max(x [, axis]): 所有元素的最大值,参数是 number 或 ndarray
- np.min(x [, axis]): 所有元素的最小值,参数是 number 或 ndarray
- np.std(x [, axis]): 所有元素的标准差,参数是 number 或 ndarray
- np.var(x [, axis]): 所有元素的方差,参数是 number 或 ndarray
- np.argmax(x [, axis]): 最大值的下标索引值,参数是 number 或 ndarray
- np.argmin(x [, axis]): 最小值的下标索引值,参数是 number 或 ndarray
- np.cumsum(x [, axis]): 返回一个同纬度数组,每个元素都是之前所有元素的 累加和,参数是 number 或 ndarray
- np.cumprod(x [, axis]): 返回一个同纬度数组,每个元素都是之前所有元素的 累乘积,参数是 number 或 ndarray
注意多维的数组要指定统计的维度,否则默认是全部维度上统计。
>>> arr = np.arange(12).reshape(4,3)
>>> arr
array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]])
>>> np.sum(arr)
66
>>> np.sum(arr,axis=1)
array([ 3, 12, 21, 30])
>>>
2.3 条件函数
- all(iterables):如果可迭代对象iterables中所有元素为True则返回True。
- any(iterables):如果可迭代对象iterables中任意存在每一个元素为True则返回True。
- unique(iterables):从可迭代对象iterables中找到唯一值(去重)并返回排序结果
- where(condition, [x, y], /):返回从x或者y中过滤后的元素
>>> arr =np.array([[1,2],[2,4]])
>>> arr
array([[1, 2],
[2, 4]])
>>> np.all(arr)
True
>>> np.any(arr)
True
>>> np.unique(arr)
array([1, 2, 4])
>>>
# where
a = np.arange(10)
a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
np.where(a < 5, a, 10*a)
array([ 0, 1, 2, 3, 4, 50, 60, 70, 80, 90])
2.4 文件存储函数
当进行数组操作后需要将数组的内容进行保存,此时需要用到文件存储的函数。
savetxtloadtxt
import numpy as np
array = np.arange(20)
#将数组array以整数形式保存到a.txt文件中
np.savetxt("a.txt",array,fmt='%d')
#将数组array以浮点数形式保存到b.txt文件中
np.savetxt("b.txt",array,fmt='%.2f')
#从a.txt文件中以整数形式读取文本数据,并返回NumPy数组
array1 = np.loadtxt("a.txt",dtype='int')
print(array1)
#从b.txt文件中以浮点数形式读取文本数据,并返回NumPy数组
array2 = np.loadtxt("b.txt",dtype='float')
print(array2)
savetxt和loadtxt函数也是可以读写CSV文件,CSV文件是用分隔符分隔的文本文件,通常的分隔符包括空格、逗号、分号等;通过loadtxt函数可以读取CSV文件,通过savetxt函数可以将数组保存为CSV文件。
savetxt和loadtxt函数默认都是使用空白符(空格、制表符等)作为分隔符,但可以通过delimiter关键字参数指定分隔符,还可以通过usecols关键字参数将读取的数据拆分成多列返回,列索引从0开始。
import numpy as np
array = np.arange(12).reshape(3,4)
print(array)
#将二维数组保存到c.csv文件中,并用逗号分隔
np.savetxt("c.csv",array,fmt="%d",delimiter=',')
#从c.csv文件以整数类型读取文本,并且获取第1,3列的数据
array3 = np.loadtxt("c.csv",dtype=int,delimiter=",",usecols=(0,2))
print(array3)
#将上述获取的第1,3列数据赋值给x,y变量,必须将unpack=True
x,y = np.loadtxt("c.csv",dtype=int,delimiter=",",usecols=(0,2),unpack=True)
print(x,y)
三、广播
(一)什么是广播
广播(Broadcasting)描述了 numpy 如何在算术运算期间处理具有不同形状的数组。受某些约束的影响,较小的数组在较大的数组上“广播”,以便它们具有兼容的形状。
在最简单的情况下,两个数组必须具有完全相同的形状,如下例所示:
>>> a = np.array([1.0, 2.0, 3.0])
>>> b = np.array([2.0, 2.0, 2.0])
>>> a * b
array([ 2., 4., 6.])
当一个数组和一个标量值在一个操作中组合时,会发生最简单的广播示例:
>>> a = np.array([1.0, 2.0, 3.0])
>>> b = 2.0
>>> a * b
array([ 2., 4., 6.])
结果等同于前面的示例,其中b是数组。我们可以将在算术运算期间b被 拉伸 的标量想象成具有相同形状的数组a。新元素 b只是原始标量的副本。拉伸类比只是概念性的。NumPy足够聪明,可以使用原始标量值而无需实际制作副本,因此广播操作尽可能具有内存和计算效率。
第二个示例中的代码比第一个示例中的代码更有效,因为广播在乘法期间移动的内存较少(b是标量而不是数组)。
(二)广播规则
有两种情况可以触发 NumPy 的广播机制:
- 后缘维度的轴长相等
- 轴长不相等的情况下每个数组有一个轴长为 1
1、后缘维度轴长相等
指从后向前算起的维度,轴长即其长度,也就是 shape 返回值中对应维度的数值。
>>> x = np.arange(5)
>>> x
array([0, 1, 2, 3, 4])
>>> y = np.arange(15).reshape(3,5)
>>> y
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14]])
>>> x + y
array([[ 0, 2, 4, 6, 8],
[ 5, 7, 9, 11, 13],
[10, 12, 14, 16, 18]])
其中 y 的形状为(3,5),x 的形状为(5,),二者之所以可以相加是因为其后缘维度的轴长均为 5,所以可以通过广播机制来扩充 x 以适应 y。
2、轴长不相等的情况下每个数组有一个轴长为 1
>>> y = np.arange(15).reshape(3,5)
>>> y
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14]])
>>> z = np.arange(3).reshape(3,1)
>>> z
array([[0],
[1],
[2]])
>>> y + z
array([[ 0, 1, 2, 3, 4],
[ 6, 7, 8, 9, 10],
[12, 13, 14, 15, 16]])
>>>
二者的形状为(3, 5)和(3,1),均属于二维数组,但其后缘维度的轴长不同,一个为 5 ,一个为 1,这种情况也是可以通过扩充长度为 1 的轴来适应大的形状的数组。
当然也支持两个数组同时扩张的情况,如:(1, 5)和(3, 1)扩充为 (3, 5)
3、图例
图例演示更为贴切,如下:
>>> a = np.array([1.0, 2.0, 3.0])
>>> b = np.array([2.0, 2.0, 2.0])
>>> a * b
array([ 2., 4., 6.])
>>> a = np.array([[ 0.0, 0.0, 0.0],
[10.0, 10.0, 10.0],
[20.0, 20.0, 20.0],
[30.0, 30.0, 30.0]])
>>> b = np.array([1.0, 2.0, 3.0])
>>> a + b
array([[ 1., 2., 3.],
[11., 12., 13.],
[21., 22., 23.],
[31., 32., 33.]])
>>> a = np.array([0.0, 10.0, 20.0, 30.0])
>>> b = np.array([1.0, 2.0, 3.0])
>>> a[:, np.newaxis] + b
array([[ 1., 2., 3.],
[11., 12., 13.],
[21., 22., 23.],
[31., 32., 33.]])
四、应用
(一)数学
1、三角函数
| method | description |
|---|---|
| sin(x, /[, out, where, casting, order, …]) | 正弦函数, element-wise. |
| cos(x, /[, out, where, casting, order, …]) | 余弦函数 element-wise. |
| tan(x, /[, out, where, casting, order, …]) | 正切函数, element-wise. |
| arcsin(x, /[, out, where, casting, order, …]) | 反正弦函数, element-wise. |
| arccos(x, /[, out, where, casting, order, …]) | 反余弦函数, element-wise. |
| arctan(x, /[, out, where, casting, order, …]) | 反正切函数, element-wise. |
| hypot(x1, x2, /[, out, where, casting, …]) | 传入直角三角形的“直角边”,返回其斜边。 |
| arctan2(x1, x2, /[, out, where, casting, …]) | x1 / x2的 Element-wise 反正切线正确选择象限。 |
| degrees(x, /[, out, where, casting, order, …]) | 将角度从弧度转换为度。 |
| radians(x, /[, out, where, casting, order, …]) | 将角度从度转换为弧度。 |
| unwrap(p[, discont, axis]) | 通过将值之间的增量更改为2 * pi来展开。 |
| deg2rad(x, /[, out, where, casting, order, …]) | 将角度从度转换为弧度。 |
| rad2deg(x, /[, out, where, casting, order, …]) | 将角度从弧度转换为度。 |
2、双曲函数
| method | description |
|---|---|
| sinh(x, /[, out, where, casting, order, …]) | 双曲正弦, element-wise. |
| cosh(x, /[, out, where, casting, order, …]) | 双曲余弦, element-wise. |
| tanh(x, /[, out, where, casting, order, …]) | 计算双曲正切 element-wise. |
| arcsinh(x, /[, out, where, casting, order, …]) | 反双曲正弦 element-wise. |
| arccosh(x, /[, out, where, casting, order, …]) | 反双曲余弦, element-wise. |
| arctanh(x, /[, out, where, casting, order, …]) | 反双曲正切 element-wise. |
3、四舍五入
| method | description |
|---|---|
| around(a[, decimals, out]) | 平均舍入到给定的小数位数。 |
| round_(a[, decimals, out]) | 将数组舍入到给定的小数位数。 |
| rint(x, /[, out, where, casting, order, …]) | 将数组的元素四舍五入到最接近的整数。 |
| fix(x[, out]) | 四舍五入为零。 |
| floor(x, /[, out, where, casting, order, …]) | 返回输入的底限, element-wise. |
| ceil(x, /[, out, where, casting, order, …]) | 返回输入的上限, element-wise. |
| trunc(x, /[, out, where, casting, order, …]) | 返回输入的截断值, element-wise. |
4、加法函数, 乘法函数, 减法函数
| method | description |
|---|---|
| prod(a[, axis, dtype, out, keepdims, …]) | 返回给定轴上数组元素的乘积。 |
| sum(a[, axis, dtype, out, keepdims, …]) | 给定轴上的数组元素的总和。 |
| nanprod(a[, axis, dtype, out, keepdims]) | 返回数组元素在给定轴上的乘积,将非数字(NaNs)视为一个。 |
| nansum(a[, axis, dtype, out, keepdims]) | 返回给定轴上的数组元素的总和,将非数字(NaNs)视为零。 |
| cumprod(a[, axis, dtype, out]) | 返回沿给定轴的元素的累加乘积。 |
| cumsum(a[, axis, dtype, out]) | 返回沿给定轴的元素的累加和。 |
| nancumprod(a[, axis, dtype, out]) | 返回数组元素在给定轴上的累积乘积,将非数字(NaNs)视为一个。 |
| nancumsum(a[, axis, dtype, out]) | 返回在给定轴上将非数字(NaNs)视为零的数组元素的累积总和。 |
| diff(a[, n, axis, prepend, append]) | 计算沿给定轴的第n个离散差。 |
| ediff1d(ary[, to_end, to_begin]) | 数组的连续元素之间的差值。 |
| gradient(f, *varargs, **kwargs) | 返回N维数组的梯度。 |
| cross(a, b[, axisa, axisb, axisc, axis]) | 返回两个(数组)向量的叉积。 |
| trapz(y[, x, dx, axis]) | 使用复合梯形规则沿给定轴积分。 |
5、指数和对数
| method | description |
|---|---|
| exp(x, /[, out, where, casting, order, …]) | 计算输入数组中所有元素的指数。 |
| expm1(x, /[, out, where, casting, order, …]) | 为数组中的所有元素计算exp(x)-1。 |
| exp2(x, /[, out, where, casting, order, …]) | 为输入数组中的所有p计算2 ** p。 |
| log(x, /[, out, where, casting, order, …]) | 自然对数, element-wise. |
| log10(x, /[, out, where, casting, order, …]) | 返回输入数组的以10为底的对数, element-wise. |
| log2(x, /[, out, where, casting, order, …]) | x的以2为底的对数。 |
| log1p(x, /[, out, where, casting, order, …]) | 返回元素加一个输入数组的自然对数。 |
| logaddexp(x1, x2, /[, out, where, casting, …]) | 输入取幂之和的对数。 |
| logaddexp2(x1, x2, /[, out, where, casting, …]) | 以2为底的输入的幂和的对数。 |
6、其他特殊函数
| method | description |
|---|---|
| i0(x) | 第一种修改的Bessel函数,阶数为0。 |
| sinc(x) | 返回sinc函数。 |
7、浮点例程
| method | description |
|---|---|
| signbit(x, /[, out, where, casting, order, …]) | 在设置了符号位(小于零)的情况下返回 element-wise True。 |
| copysign(x1, x2, /[, out, where, casting, …]) | 将x1的符号更改为x2的符号, element-wise. |
| frexp(x[, out1, out2], / [[, out, where, …]) | 将x的元素分解为尾数和二进制指数。 |
| ldexp(x1, x2, /[, out, where, casting, …]) | 返回x1 * 2 ** x2, element-wise. |
| nextafter(x1, x2, /[, out, where, casting, …]) | 向x2返回x1之后的下一个浮点值, element-wise. |
| spacing(x, /[, out, where, casting, order, …]) | 返回x与最近的相邻数字之间的距离。 |
8、理性例程
| method | description |
|---|---|
| lcm(x1, x2, /[, out, where, casting, order, …]) | 返回1和x2的最小公倍数 |
| gcd(x1, x2, /[, out, where, casting, order, …]) | 返回x1和x2的最大公约数 |
9、算术运算
| method | description |
|---|---|
| add(x1, x2, /[, out, where, casting, order, …]) | 按元素添加参数。 |
| reciprocal(x, /[, out, where, casting, …]) | 以元素为单位返回参数的倒数。 |
| positive(x, /[, out, where, casting, order, …]) | 数值正, element-wise. |
| negative(x, /[, out, where, casting, order, …]) | 数值负数, element-wise. |
| multiply(x1, x2, /[, out, where, casting, …]) | 逐个乘以参数。 |
| divide(x1, x2, /[, out, where, casting, …]) | 返回输入的真实除法, element-wise. |
| power(x1, x2, /[, out, where, casting, …]) | 第一阵列元素从第二阵列提升为幂, element-wise. |
| subtract(x1, x2, /[, out, where, casting, …]) | 逐个元素地减去参数。 |
| true_divide(x1, x2, /[, out, where, …]) | 返回输入的真实除法, element-wise. |
| floor_divide(x1, x2, /[, out, where, …]) | 返回小于或等于输入的除法的最大整数。 |
| float_power(x1, x2, /[, out, where, …]) | 第一阵列元素从第二阵列提升为幂, element-wise. |
| fmod(x1, x2, /[, out, where, casting, …]) | 返回元素的除法 remainder。 |
| mod(x1, x2, /[, out, where, casting, order, …]) | 返回元素的除法余数。 |
| modf(x[, out1, out2], / [[, out, where, …]) | 返回数组的分数和整数部分, element-wise. |
| remainder(x1, x2, /[, out, where, casting, …]) | 返回元素的除法余数。 |
| divmod(x1, x2[, out1, out2], / [[, out, …]) | 同时返回按元素商和余数。 |
10 、处理复数
| method | description |
|---|---|
| angle(z[, deg]) | 返回复杂参数的角度。 |
| real(val) | 返回复杂参数的实部。 |
| imag(val) | 返回复杂参数的虚部。 |
| conj(x, /[, out, where, casting, order, …]) | 返回 complex conjugate, element-wise. |
| conjugate(x, /[, out, where, casting, …]) | 返回复共轭, element-wise. |
11、其它
| method | description |
|---|---|
| convolve(a, v[, mode]) | 返回两个一维序列的离散线性卷积。 |
| clip(a, a_min, a_max[, out]) | 裁剪(限制)数组中的值。 |
| sqrt(x, /[, out, where, casting, order, …]) | 返回数组的非负 平方根, element-wise. |
| cbrt(x, /[, out, where, casting, order, …]) | 返回数组的立方根, element-wise. |
| square(x, /[, out, where, casting, order, …]) | 返回输入的元素方平方。 |
| absolute(x, /[, out, where, casting, order, …]) | 计算绝对值 element-wise. |
| fabs(x, /[, out, where, casting, order, …]) | 计算绝对值 element-wise. |
| sign(x, /[, out, where, casting, order, …]) | 返回数字符号的逐元素指示。 |
| heaviside(x1, x2, /[, out, where, casting, …]) | 计算Heaviside阶跃函数。 |
| maximum(x1, x2, /[, out, where, casting, …]) | 数组元素的逐元素最大值。 |
| minimum(x1, x2, /[, out, where, casting, …]) | 数组元素的按元素最小值。 |
| fmax(x1, x2, /[, out, where, casting, …]) | 数组元素的逐元素最大值。 |
| fmin(x1, x2, /[, out, where, casting, …]) | 数组元素的按元素最小值。 |
| nan_to_num(x[, copy, nan, posinf, neginf]) | 用较大的有限数字(默认行为)或使用用户定义的nan,posinf和/或neginf关键字定义的数字将NaN替换为零和无穷大。 |
| real_if_close(a[, tol]) | 如果复杂输入接近实数,则返回复杂数组。 |
| interp(x, xp, fp[, left, right, period]) | 一维线性插值。 |
12、代码
# 单值
>>> np.sin(np.pi/2.)
1.0
# 多值
>>> np.sin(np.array((0., 30., 45., 60., 90.)) * np.pi / 180. )
array([ 0. , 0.5 , 0.70710678, 0.8660254 , 1. ])
# 图像
import matplotlib.pylab as plt
>>> x = np.linspace(-np.pi, np.pi, 201)
>>> plt.plot(x, np.sin(x))
>>> plt.xlabel('Angle [rad]')
>>> plt.ylabel('sin(x)')
>>> plt.axis('tight')
>>> plt.show()
(二)线性代数(numpy.linalg)
NumPy线性代数函数依赖于BLAS和LAPACK来提供标准线性代数算法的高效低级实现。 这些库可以由NumPy本身使用其参考实现子集的C版本提供, 但如果可能,最好是利用专用处理器功能的高度优化的库。 这样的库的例子是OpenBLAS、MKL(TM)和ATLAS。因为这些库是多线程和处理器相关的, 所以可能需要环境变量和外部包(如threadpoolctl)来控制线程数量或指定处理器体系结构。
1、矩阵和向量积
| 方法 | 描述 |
|---|---|
| dot(a, b[, out]) | 两个数组的点积。 |
| linalg.multi_dot(arrays) | 在单个函数调用中计算两个或更多数组的点积,同时自动选择最快的求值顺序。 |
| vdot(a, b) | 返回两个向量的点积。 |
| inner(a, b) | 两个数组的内积。 |
| outer(a, b[, out]) | 计算两个向量的外积。 |
| matmul(x1, x2, /[, out, casting, order, …]) | 两个数组的矩阵乘积。 |
| tensordot(a, b[, axes]) | 沿指定轴计算张量点积。 |
| einsum(subscripts, *operands[, out, dtype, …]) | 计算操作数上的爱因斯坦求和约定。 |
| einsum_path(subscripts, *operands[, optimize]) | 通过考虑中间数组的创建,计算einsum表达式的最低成本压缩顺序。 |
| linalg.matrix_power(a, n) | 将方阵提升为(整数)n次方。 |
| kron(a, b) | 两个数组的Kronecker乘积。 |
2、分解
| 方法 | 描述 |
|---|---|
| linalg.cholesky(a) | Cholesky分解 |
| linalg.qr(a[, mode]) | 计算矩阵的QR分解。 |
| linalg.svd(a[, full_matrices, compute_uv, …]) | 奇异值分解 |
3、矩阵特征值
| 方法 | 描述 |
|---|---|
| linalg.eig(a) | 计算方阵的特征值和右特征向量。 |
| linalg.eigh(a[, UPLO]) | 返回复数Hermitian(共轭对称)或实对称矩阵的特征值和特征向量。 |
| linalg.eigvals(a) | 计算通用矩阵的特征值。 |
| linalg.eigvalsh(a[, UPLO]) | 计算复杂的Hermitian或实对称矩阵的特征值。 |
4、范数和其他数字
| 方法 | 描述 |
|---|---|
| linalg.norm(x[, ord, axis, keepdims]) | 矩阵或向量范数。 |
| linalg.cond(x[, p]) | 计算矩阵的条件数。 |
| linalg.det(a) | 计算数组的行列式。 |
| linalg.matrix_rank(M[, tol, hermitian]) | 使用SVD方法返回数组的矩阵的rank |
| linalg.slogdet(a) | 计算数组行列式的符号和(自然)对数。 |
| trace(a[, offset, axis1, axis2, dtype, out]) | 返回数组对角线的和。 |
5、解方程和逆矩阵
| 方法 | 描述 |
|---|---|
| linalg.solve(a, b) | 求解线性矩阵方程或线性标量方程组。 |
| linalg.tensorsolve(a, b[, axes]) | 对x求解张量方程a x = b。 |
| linalg.lstsq(a, b[, rcond]) | 返回线性矩阵方程的最小二乘解。 |
| linalg.inv(a) | 计算矩阵的(乘法)逆。 |
| linalg.pinv(a[, rcond, hermitian]) | 计算矩阵的(Moore-Penrose)伪逆。 |
| linalg.tensorinv(a[, ind]) | 计算N维数组的“逆”。 |
6、其它
| 方法 | 描述 |
|---|---|
| linalg.LinAlgError | 泛型Python-linalg函数引发的异常派生对 |
7、代码
# np.dot
>>> a = [[1, 0], [0, 1]]
>>> b = [[4, 1], [2, 2]]
>>> np.dot(a, b)
array([[4, 1],
[2, 2]])
# np.vdot
>>> a = np.array([[1, 4], [5, 6]])
>>> b = np.array([[4, 1], [2, 2]])
>>> np.vdot(a, b)
30
>>> np.vdot(b, a)
30
>>> 1*4 + 4*1 + 5*2 + 6*2
30
更多详见:numpy.linalg


浙公网安备 33010602011771号