NumPy 介绍
NumPy是一个Python包。 它代表’Numerical Python’。 它是一个由多维数组对象和一组处理数组的例程组成的库。
Numeric,NumPy的祖先,由Jim Hugunin开发。 Numarray的另一个软件包也被开发出来,具有一些额外的功能。 2005年,Travis Oliphant创建了NumPy包,将Numarray的特性合并到数字包中。 这个开源项目有许多贡献者。
使用NumPy的操作
使用NumPy,开发人员可以执行以下操作 –
- 数组的数学和逻辑运算。
- 傅立叶变换和形状操作的例程。
- 与线性代数有关的操作。 NumPy具有用于线性代数和随机数生成的内置函数。
NumPy – MatLab的替代品
NumPy通常与SciPy(Scientific Python)和Mat-plotlib(绘图库)等软件包一起使用。 这种组合广泛用于替代技术计算的流行平台MatLab。 然而,MatLab的Python替代品现在被视为更现代和完整的编程语言。
它是开源的,这是NumPy的一个附加优势。
NumPy 环境安装
标准Python发行版不捆绑NumPy模块。 一种轻量级的选择是使用流行的Python包安装程序pip来安装NumPy。
pip install numpy
启用NumPy的最佳方式是使用特定于您的操作系统的可安装二进制包。 这些二进制文件包含完整的SciPy堆栈(包括NumPy,SciPy,matplotlib,IPython,SymPy和nose包以及核心Python)。
Windows
Anaconda(来自www.continuum.io)是SciPy堆栈的免费Python发行版。 它也适用于Linux和Mac。
Canopy(www.enthought.com/products/canopy/)免费提供,并提供完整的用于Windows,Linux和Mac的SciPy堆栈的商业分发。
Python(x,y):这是一个免费的Python发行版,其中包含用于Windows操作系统的SciPy堆栈和Spyder IDE。 (可从www.python-xy.github.io/下载)
Linux
各个Linux发行版的软件包管理器用于在SciPy堆栈中安装一个或多个软件包。
Ubuntu
sudo apt-get install python-numpy python-scipy python-matplotlibipythonipythonnotebook python-pandas python-sympy python-nose
Fedora
sudo yum install numpyscipy python-matplotlibipython python-pandas sympy python-nose atlas-devel
从源代码构建
Core Python(2.6.x,2.7.x和3.2.x以上)必须与distutils一起安装,并且应启用zlib模块。
GNU gcc(4.2及更高版本)C编译器必须可用。
要安装NumPy,请运行以下命令。
Python setup.py install
要测试NumPy模块是否正确安装,请尝试从Python提示符导入它。
如果未安装,则会显示以下错误消息。
Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> import numpy ImportError: No module named 'numpy'
NumPy Ndarray对象
NumPy中定义的最重要的对象是名为ndarray的N维数组类型。 它描述了相同类型的项目的集合。 可以使用从零开始的索引来访问集合中的项目。
ndarray中的每个项目在内存中占用相同的块大小。 ndarray中的每个元素都是数据类型对象(称为dtype)的对象。
从ndarray对象中提取的任何项目(通过切片)由数组标量类型之一的Python对象表示。 下图显示了ndarray,数据类型对象(dtype)和数组标量类型之间的关系 –
ndarray类的一个实例可以通过本教程稍后介绍的不同阵列创建例程来构建。 基本的ndarray是使用NumPy中的数组函数创建的,如下所示 –
numpy.array
它从暴露数组接口的任何对象或任何返回数组的方法创建一个ndarray。
numpy.array(object, dtype = None, copy = True, order = None, subok = False, ndmin = 0)
上面的构造函数采用以下参数 –
序号 | 参数 & 描述 |
---|---|
1 | object 任何暴露数组接口方法的对象都会返回一个数组或任何(嵌套)序列。 |
2 | dtype 数组的期望数据类型,可选 |
3 | copy 可选的。 默认情况下(true),对象被复制 |
4 | order C(行主)或F(列主)或A(任何)(默认) |
5 | subok 默认情况下,返回的数组被强制为基类数组。 如果为true,则通过子类 |
6 | ndmin 指定结果数组的最小维数 |
看看下面的例子来更好地理解。
例1
import numpy as np a = np.array([1,2,3]) print a
输出如下 –
[1, 2, 3]
例2
# more than one dimensions import numpy as np a = np.array([[1, 2], [3, 4]]) print a
输出如下 –
[[1, 2] [3, 4]]
例3
# minimum dimensions import numpy as np a = np.array([1, 2, 3,4,5], ndmin = 2) print a
输出如下 –
[[1, 2, 3, 4, 5]]
例4
# dtype parameter import numpy as np a = np.array([1, 2, 3], dtype = complex) print a
输出如下 –
[ 1.+0.j, 2.+0.j, 3.+0.j]
ndarray对象由计算机内存的连续一维片段组成,并将索引方案与每个项目映射到内存块中的位置相结合。 内存块以行主要顺序(C风格)或列主要顺序(FORTRAN或MatLab风格)保存元素。
NumPy 数据类型
NumPy支持比Python更多的数字类型。 下表显示了在NumPy中定义的不同标量数据类型。
序号 | 数据类型 & 描述 |
---|---|
1 | bool_ 布尔(True或False)存储为一个字节 |
2 | int_ 默认整数类型(与C long相同;通常是int64或int32) |
3 | intc 与C int相同(通常为int32或int64) |
4 | intp 用于索引的整数(与C ssize_t相同;通常为int32或int64) |
5 | int8 字节(-128至127) |
6 | int16 整数(-32768至32767) |
7 | int32 整数(-2147483648至2147483647) |
8 | int64
整数(-9223372036854775808至9223372036854775807) |
9 | uint8 无符号整数(0到255) |
10 | uint16 无符号整数(0到65535) |
11 | uint32 无符号整数(0到4294967295) |
12 | uint64 无符号整数(0到18446744073709551615) |
13 | float_ 同float64 |
14 | float16 半精度浮点:符号位,5位指数,10位尾数 |
15 | float32 单精度浮点数:符号位,8位指数,23位尾数 |
16 | float64 双精度浮点:符号位,11位指数,52位尾数 |
17 | complex_ 同complex128 |
18 | complex64 复数,由两个32位浮点数(实部和虚部) |
19 | complex128 复数,由两个64位浮点数(实部和虚部) |
NumPy数字类型是dtype(数据类型)对象的实例,每个对象都有独特的特征。 该dtypes可用作np.bool_,np.float32等。
数据类型对象(dtype)
数据类型对象根据以下几个方面描述对应于数组的固定内存块的解释 –
- 数据类型(整型,浮点型或Python对象)
- 数据的大小
- 字节顺序(小端或大端)
- 在结构化类型的情况下,字段的名称,每个字段的数据类型和每个字段占用的存储器块的一部分。
- 如果数据类型是子阵列,则它的形状和数据类型
字节顺序由前缀’&lt;’决定 或’&gt;’ 到数据类型。’&LT;’ 意味着编码是小端(最小有效存储在最小地址中)。’&GT;’ 意味着编码是big-endian(最重要的字节存储在最小地址中)。
一个dtype对象使用下面的语法&minus构造出来;
numpy.dtype(object, align, copy)
参数是 –
- Object − 被转换为数据类型对象
- Align − 如果为true,则向该字段添加填充以使其类似于C-struct
- Copy − 生成一个新的dtype对象。 如果为false,则结果是对内置数据类型对象的引用
例1
# using array-scalar type import numpy as np dt = np.dtype(np.int32) print dt
输出如下 –
int32
例2
#int8, int16, int32, int64 can be replaced by equivalent string 'i1', 'i2','i4', etc. import numpy as np dt = np.dtype('i4') print dt
输出如下 –
int32
例3
# using endian notation import numpy as np dt = np.dtype('>i4') print dt
输出如下 –
>i4
例4
# first create structured data type import numpy as np dt = np.dtype([('age',np.int8)]) print dt
输出如下 –
[('age', 'i1')]
例5
# now apply it to ndarray object import numpy as np dt = np.dtype([('age',np.int8)]) a = np.array([(10,),(20,),(30,)], dtype = dt) print a
输出如下 –
[(10,) (20,) (30,)]
例6
# file name can be used to access content of age column import numpy as np dt = np.dtype([('age',np.int8)]) a = np.array([(10,),(20,),(30,)], dtype = dt) print a['age']
输出如下 –
[10 20 30]
例7
以下示例定义了一个名为student的结构化数据类型,其中包含一个字符串字段’name’,一个整数字段’age’和一个浮点字段’marks’。 这个dtype被应用于ndarray对象。
import numpy as np student = np.dtype([('name','S20'), ('age', 'i1'), ('marks', 'f4')]) print student
输出如下 –
[('name', 'S20'), ('age', 'i1'), ('marks', '<f4')])
例8
import numpy as np student = np.dtype([('name','S20'), ('age', 'i1'), ('marks', 'f4')]) a = np.array([('abc', 21, 50),('xyz', 18, 75)], dtype = student) print a
输出如下 –
[('abc', 21, 50.0), ('xyz', 18, 75.0)]
每个内置数据类型都有一个唯一标识它的字符代码。
- ‘b’ − boolean
- ‘i’ − (signed) integer
- ‘u’ − unsigned integer
- ‘f’ − floating-point
- ‘c’ − complex-floating point
- ‘m’ − timedelta
- ‘M’ − datetime
- ‘O’ − (Python) objects
- ‘S’, ‘a’ − (byte-)string
- ‘U’ − Unicode
- ‘V’ − raw data (void)
NumPy 数组属性
在本章中,我们将讨论NumPy的各种数组属性。
ndarray.shape
这个数组属性返回一个由数组维度组成的元组。 它也可以用来调整数组的大小。
例1
import numpy as np a = np.array([[1,2,3],[4,5,6]]) print a.shape
输出如下 –
(2, 3)
例2
# this resizes the ndarray import numpy as np a = np.array([[1,2,3],[4,5,6]]) a.shape = (3,2) print a
输出如下 –
[[1, 2] [3, 4] [5, 6]]
例3
NumPy还提供了一个调整数组大小的整形功能。
import numpy as np a = np.array([[1,2,3],[4,5,6]]) b = a.reshape(3,2) print b
输出如下 –
[[1, 2] [3, 4] [5, 6]]
ndarray.ndim
该数组属性返回数组维数。
例1
# an array of evenly spaced numbers import numpy as np a = np.arange(24) print a
输出如下 –
[0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23]
例2
# this is one dimensional array import numpy as np a = np.arange(24) a.ndim # now reshape it b = a.reshape(2,4,3) print b # b is having three dimensions
输出如下 –
[[[ 0, 1, 2] [ 3, 4, 5] [ 6, 7, 8] [ 9, 10, 11]] [[12, 13, 14] [15, 16, 17] [18, 19, 20] [21, 22, 23]]]
numpy.itemsize
这个数组属性以字节为单位返回数组中每个元素的长度。
例1
# dtype of array is int8 (1 byte) import numpy as np x = np.array([1,2,3,4,5], dtype = np.int8) print x.itemsize
输出如下 –
1
例2
# dtype of array is now float32 (4 bytes) import numpy as np x = np.array([1,2,3,4,5], dtype = np.float32) print x.itemsize
输出如下 –
4
numpy.flags
ndarray对象具有以下属性。 它的当前值由这个函数返回。
序号 | 属性 & 描述 |
---|---|
1 | C_CONTIGUOUS (C) 数据在一个单一的,C风格的连续段 |
2 | F_CONTIGUOUS (F) 这些数据位于一个Fortran风格的连续分段中 |
3 | OWNDATA (O) 数组拥有它使用的内存或从另一个对象中借用内存 |
4 | WRITEABLE (W) 数据区可以写入。 将其设置为False会锁定数据,使其成为只读 |
5 | ALIGNED (A) 数据和所有元素都针对硬件进行了适当的对齐 |
6 | UPDATEIFCOPY (U) 这个数组是其他数组的副本。 当这个数组被解除分配时,基数组将被更新为这个数组的内容 |
以下示例显示标志的当前值。
import numpy as np x = np.array([1,2,3,4,5]) print x.flags
输出如下 –
C_CONTIGUOUS : True F_CONTIGUOUS : True OWNDATA : True WRITEABLE : True ALIGNED : True UPDATEIFCOPY : False
NumPy 生成数组函数
新的ndarray对象可以通过以下任何生成数组函数或使用低级别的ndarray构造函数构造。
numpy.empty
它创建一个未初始化的指定形状和dtype数组。 它使用以下构造函数 –
numpy.empty(shape, dtype = float, order = 'C')
构造函数采用以下参数。
序号 | 参数 & 描述 |
---|---|
1 | Shape 整数或者整型元组,定义返回数组的形状 |
2 | Dtype 数据类型,可选定义返回数组的类型。 |
3 | Order {‘C’, ‘F’}, 可选规定返回数组元素在内存的存储顺序:C(C语言)-rowmajor;F(Fortran)column-major。 |
例子
以下代码显示了一个空数组的示例。
import numpy as np x = np.empty([3,2], dtype = int) print x
输出如下 –
[[22649312 1701344351] [1818321759 1885959276] [16779776 156368896]]
注 – 数组中的元素显示随机值,因为它们未被初始化。
numpy.zeros
返回指定大小的新数组,填充零。
numpy.zeros(shape, dtype = float, order = 'C')
构造函数采用以下参数。
序号 | 参数 & 描述 |
---|---|
1 | Shape 整数或者整型元组,定义返回数组的形状 |
2 | Dtype 数据类型,可选定义返回数组的类型。 |
3 | Order {‘C’, ‘F’}, 可选规定返回数组元素在内存的存储顺序:C(C语言)-rowmajor;F(Fortran)column-major。 |
例1
# array of five zeros. Default dtype is float import numpy as np x = np.zeros(5) print x
输出如下 –
[ 0. 0. 0. 0. 0.]
例2
import numpy as np x = np.zeros((5,), dtype = np.int) print x
输出如下 –
[0 0 0 0 0]
例3
# custom type import numpy as np x = np.zeros((2,2), dtype = [('x', 'i4'), ('y', 'i4')]) print x
输出如下 –
[[(0,0)(0,0)] [(0,0)(0,0)]]
numpy.ones
返回指定大小和类型的新数组,填充1。
numpy.ones(shape, dtype = None, order = 'C')
构造函数采用以下参数。
序号 | 参数 & 描述 |
---|---|
1 | Shape 整数或者整型元组,定义返回数组的形状 |
2 | Dtype 数据类型,可选定义返回数组的类型。 |
3 | Order {‘C’, ‘F’}, 可选规定返回数组元素在内存的存储顺序:C(C语言)-rowmajor;F(Fortran)column-major。 |
例1
# array of five ones. Default dtype is float import numpy as np x = np.ones(5) print x
输出如下 –
[ 1. 1. 1. 1. 1.]
例2
import numpy as np x = np.ones([2,2], dtype = int) print x
输出如下 –
[[1 1] [1 1]]
NumPy 创建数组(从现存数据)
在本章中,我们将讨论如何从现有数据创建一个数组。
numpy.asarray
这个函数与numpy.array类似,只是它的参数较少。 此例程对于将Python序列转换为ndarray很有用。
numpy.asarray(a, dtype = None, order = None)
构造函数采用以下参数。
序号 | 参数 & 描述 |
---|---|
1 | a 以任何形式输入数据,如列表,元组列表,元组列表,元组元组或元组元组 |
2 | dtype 默认情况下,输入数据的数据类型应用于ndarray |
3 | order C(row-major 行序优先)或F(column-major 列序优先)。 C是默认的 |
以下示例显示如何使用asarray函数。
例1
# convert list to ndarray import numpy as np x = [1,2,3] a = np.asarray(x) print a
执行结果如下 –
[1 2 3]
例2
# dtype is set import numpy as np x = [1,2,3] a = np.asarray(x, dtype = float) print a
执行结果如下 –
[ 1. 2. 3.]
例3
# ndarray from tuple import numpy as np x = (1,2,3) a = np.asarray(x) print a
执行结果如下 –
[1 2 3]
例4
# ndarray from list of tuples import numpy as np x = [(1,2,3),(4,5)] a = np.asarray(x) print a
执行结果如下 –
[(1, 2, 3) (4, 5)]
numpy.frombuffer
该函数将缓冲区解释为一维数组。 公开缓冲区接口的任何对象都将用作返回ndarray的参数。
numpy.frombuffer(buffer, dtype = float, count = -1, offset = 0)
构造函数采用以下参数。
序号 | 参数 & 描述 |
---|---|
1 | buffer 任何公开缓冲区接口的对象 |
2 | dtype 返回的ndarray的数据类型。 默认为浮点 |
3 | count 要读取的数量,默认值-1表示所有数据 |
4 | offset 读取的起始位置。 缺省值是0 |
例子
以下示例演示使用frombuffer函数。
import numpy as np s = 'Hello World' a = np.frombuffer(s, dtype = 'S1') print a
执行结果如下 –
['H' 'e' 'l' 'l' 'o' ' ' 'W' 'o' 'r' 'l' 'd']
numpy.fromiter
该函数从任何可迭代对象构建一个ndarray对象。 这个函数返回一个新的一维数组。
numpy.fromiter(iterable, dtype, count = -1)
这里,构造函数接受以下参数。
序号 | 参数 & 描述 |
---|---|
1 | iterable 任何可迭代的对象 |
2 | dtype 结果数组的数据类型 |
3 | count 要从迭代器读取的项目数量。 默认值是-1,这意味着所有要读取的数据 |
以下示例显示如何使用内置的range()函数返回列表对象。 这个列表的迭代器用于形成一个ndarray对象。
例1
# create list object using range function import numpy as np list = range(5) print list
执行结果如下 –
[0, 1, 2, 3, 4]
例2
# obtain iterator object from list import numpy as np list = range(5) it = iter(list) # use iterator to create ndarray x = np.fromiter(it, dtype = float) print x
执行结果如下 –
[0. 1. 2. 3. 4.]
NumPy 创建数组(从数值范围)
在本章中,我们将看到如何从数值范围创建一个数组。
numpy.arange
该函数返回一个包含给定范围内均匀间隔值的ndarray对象。 该功能的格式如下 –
numpy.arange(start, stop, step, dtype)
构造函数采用以下参数。
序号 | 参数 & 描述 |
---|---|
1 | start 间隔的开始。 如果省略,则默认为0 |
2 | stop 间隔结束(不包括此数字) |
3 | step 值之间的间距,默认值为1 |
4 | dtype 生成的ndarray的数据类型。 如果没有给出,则使用输入的数据类型 |
以下示例显示如何使用此功能。
例1
import numpy as np x = np.arange(5) print x
执行结果如下 –
[0 1 2 3 4]
例2
import numpy as np # dtype set x = np.arange(5, dtype = float) print x
执行结果如下 –
[0. 1. 2. 3. 4.]
例3
# start and stop parameters set import numpy as np x = np.arange(10,20,2) print x
执行结果如下 –
[10 12 14 16 18]
numpy.linspace
该函数与arange()函数类似。 在此函数中,不是步长,而是指定间隔之间的均匀间隔值的数量。 该功能的用法如下 –
numpy.linspace(start, stop, num, endpoint, retstep, dtype)
构造函数采用以下参数。
序号 | 参数 & 描述 |
---|---|
1 | start 序列的起始值 |
2 | stop 序列的结束值,包括在端点设置为true的序列中 |
3 | num 要生成的均匀间隔样本的数量。 默认值是50 |
4 | endpoint 如果为真,则最后一个值(stop对应的值)包含在样本中 |
5 | retstep 如果为真,返回样本及步长 |
6 | dtype 输出ndarray的数据类型 |
以下示例演示了使用linspace函数。
例1
import numpy as np x = np.linspace(10,20,5) print x
执行结果如下 –
[10. 12.5 15. 17.5 20.]
例2
# endpoint set to false import numpy as np x = np.linspace(10,20, 5, endpoint = False) print x
执行结果如下 –
[10. 12. 14. 16. 18.]
例3
# find retstep value import numpy as np x = np.linspace(1,2,5, retstep = True) print x # retstep here is 0.25
执行结果如下 –
(array([ 1. , 1.25, 1.5 , 1.75, 2. ]), 0.25)
numpy.logspace
该函数返回一个ndarray对象,该对象包含在对数刻度上均匀间隔的数字。 规模的起止点是基数的指数,通常为10。
numpy.logspace(start, stop, num, endpoint, base, dtype)
以下参数决定了logspace函数的输出。
序号 | 参数 & 描述 |
---|---|
1 | start 序列的起始值是basestart |
2 | stop 序列的结束值是basestop |
3 | num 要生成的均匀间隔样本的数量。 默认值是50 |
4 | endpoint 如果为真,则最后一个值(stop对应的值)包含在样本中 |
5 | base base值,默认为10 |
6 | dtype 输出数组的数据类型。 如果没有给出,则取决于其他输入参数 |
以下示例将帮助您了解logspace功能。
例1
import numpy as np # default base is 10 a = np.logspace(1.0, 2.0, num = 10) print a
执行结果如下 –
[ 10. 12.91549665 16.68100537 21.5443469 27.82559402 35.93813664 46.41588834 59.94842503 77.42636827 100. ]
例2
# set base of log space to 2 import numpy as np a = np.logspace(1,10,num = 10, base = 2) print a
执行结果如下 –
[ 2. 4. 8. 16. 32. 64. 128. 256. 512. 1024.]
NumPy 索引和切片
可以通过索引或切片来访问和修改ndarray对象的内容,就像Python的内置容器对象一样。
如前所述,ndarray对象中的项遵循从零开始的索引。 有三种索引方法可用 – 字段访问,基本切片和高级索引。
基本切片是Python切片为n维的基本概念的扩展。 通过给内置切片函数提供start,stop和step参数来构造Python切片对象。 该切片对象被传递给数组以提取数组的一部分。
例1
import numpy as np a = np.arange(10) s = slice(2,7,2) print a[s]
结果如下-
[2 4 6]
在上面的例子中,一个ndarray对象由arange()函数准备。 然后分别用start,stop和step值2,7和2定义切片对象。 当这个slice对象被传递给ndarray时,它的一部分以索引2开始,最多为7,步长为2。
通过直接向冒号对象提供由冒号分隔的切片参数((start:stop:step)),也可以获得相同的结果。
例2
import numpy as np a = np.arange(10) b = a[2:7:2] print b
结果如下-
[2 4 6]
如果只放入一个参数,则会返回与该索引对应的单个项目。 如果将a:插入其前面,则将从该索引开始提取所有项目。 如果使用两个参数(在它们之间),则将使用默认步骤1对两个索引(不包括停止索引)之间的项目进行切片。
例3
# slice single item import numpy as np a = np.arange(10) b = a[5] print b
结果如下-
5
例4
# slice items starting from index import numpy as np a = np.arange(10) print a[2:]
结果如下-
[2 3 4 5 6 7 8 9]
例5
# slice items between indexes import numpy as np a = np.arange(10) print a[2:5]
结果如下-
[2 3 4]
以上描述也适用于多维的ndarray。
例6
import numpy as np a = np.array([[1,2,3],[3,4,5],[4,5,6]]) print a # slice items starting from index print 'Now we will slice the array from the index a[1:]' print a[1:]
结果如下-
[[1 2 3] [3 4 5] [4 5 6]] Now we will slice the array from the index a[1:] [[3 4 5] [4 5 6]]
切片还可以包含省略号(…)以制作与数组维度长度相同的选择元组。 如果在行位置使用省略号,它将返回包含行中项目的ndarray。
例7
# array to begin with import numpy as np a = np.array([[1,2,3],[3,4,5],[4,5,6]]) print 'Our array is:' print a print '\n' # this returns array of items in the second column print 'The items in the second column are:' print a[...,1] print '\n' # Now we will slice all items from the second row print 'The items in the second row are:' print a[1,...] print '\n' # Now we will slice all items from column 1 onwards print 'The items column 1 onwards are:' print a[...,1:]
结果如下-
Our array is: [[1 2 3] [3 4 5] [4 5 6]] The items in the second column are: [2 4 5] The items in the second row are: [3 4 5] The items column 1 onwards are: [[2 3] [4 5] [5 6]]
NumPy 高级索引
可以从ndarray中选择一个非元组序列,整数或布尔数据类型的ndarray对象,或者至少包含一个项目作为序列对象的元组。 高级索引始终返回数据的副本。 与此相反,切片只呈现一个视图。
有两种高级索引 – 整型和布尔型。
整数索引
该机制有助于根据其无限维索引在数组中选择任意的项目。 每个整数数组代表该维度中的索引数量。 当索引由与目标ndarray的维度相同数量的整数数组组成时,它变得非常简单。
在以下示例中,选择了从ndarray对象的每一行中指定列的一个元素。 因此,行索引包含所有行号,列索引指定要选择的元素。
例1
import numpy as np x = np.array([[1, 2], [3, 4], [5, 6]]) y = x[[0,1,2], [0,1,0]] print y
其结果如下-
[1 4 5]
选择包括第一个数组中的(0,0),(1,1)和(2,0)元素。
在以下示例中,选择放置在4X3阵列角落的元素。 选择的行索引是[0,0]和[3,3],而列索引是[0,2]和[0,2]。
例2
import numpy as np x = np.array([[ 0, 1, 2],[ 3, 4, 5],[ 6, 7, 8],[ 9, 10, 11]]) print 'Our array is:' print x print '\n' rows = np.array([[0,0],[3,3]]) cols = np.array([[0,2],[0,2]]) y = x[rows,cols] print 'The corner elements of this array are:' print y
这个程序的输出如下 –
Our array is: [[ 0 1 2] [ 3 4 5] [ 6 7 8] [ 9 10 11]] The corner elements of this array are: [[ 0 2] [ 9 11]]
最终的选择是包含角点元素的ndarray对象。
高级和基本索引可以通过使用一个slice(:)或省略号(…)与索引数组结合使用。 以下示例对列使用slice和高级索引。 当切片用于两者时结果相同。 但高级索引会导致复制,并可能有不同的内存布局。
例3
import numpy as np x = np.array([[ 0, 1, 2],[ 3, 4, 5],[ 6, 7, 8],[ 9, 10, 11]]) print 'Our array is:' print x print '\n' # slicing z = x[1:4,1:3] print 'After slicing, our array becomes:' print z print '\n' # using advanced index for column y = x[1:4,[1,2]] print 'Slicing using advanced index for column:' print y
这个程序的输出如下 –
Our array is: [[ 0 1 2] [ 3 4 5] [ 6 7 8] [ 9 10 11]] After slicing, our array becomes: [[ 4 5] [ 7 8] [10 11]] Slicing using advanced index for column: [[ 4 5] [ 7 8] [10 11]]
布尔数组索引
这种类型的高级索引是在结果对象是布尔操作的结果时使用的,例如比较运算符。
例1
在此示例中,由于布尔索引而返回大于5的项目。
import numpy as np x = np.array([[ 0, 1, 2],[ 3, 4, 5],[ 6, 7, 8],[ 9, 10, 11]]) print 'Our array is:' print x print '\n' # Now we will print the items greater than 5 print 'The items greater than 5 are:' print x[x > 5]
这个程序的输出如下 –
Our array is: [[ 0 1 2] [ 3 4 5] [ 6 7 8] [ 9 10 11]] The items greater than 5 are: [ 6 7 8 9 10 11]
例2
在这个例子中,通过使用〜(补数运算符)省略NaN(非数字)元素。
import numpy as np a = np.array([np.nan, 1,2,np.nan,3,4,5]) print a[~np.isnan(a)]
这个程序的输出如下 –
[ 1. 2. 3. 4. 5.]
例3
以下示例显示如何从数组中过滤非复数元素。
import numpy as np a = np.array([1, 2+6j, 5, 3.5+5j]) print a[np.iscomplex(a)]
这个程序的输出如下 –
[2.0+6.j 3.5+5.j]
NumPy 广播
术语广播是指在算术运算期间NumPy处理不同形状的数组的能力。 数组上的算术运算通常在相应的元素上完成。 如果两个阵列具有完全相同的形状,那么这些操作将顺利执行。
例1
import numpy as np a = np.array([1,2,3,4]) b = np.array([10,20,30,40]) c = a * b print c
该程序的输出如下 –
[10 40 90 160]
如果两个数组的维数不相同,则元素到元素的操作是不可能的。 但是,由于广播能力的原因,在NumPy中仍然可以对非相似形状的阵列进行操作。 较小的阵列被广播到较大阵列的大小,以便它们具有兼容的形状。
如果满足以下规则,广播是可能的 –
- 具有较小ndim的数组在其形状上预置为’1’。
- 输出形状的每个维度中的大小是该维度中输入大小的最大值。
- 如果输入的大小与输出大小匹配或者其值恰好为1,则可以使用输入进行计算。
- 如果输入的维度大小为1,则该维度中的第一个数据条目将用于沿该维度的所有计算。
如果上述规则产生有效结果并且以下情况之一成立,则称一组数据可以广播 –
- 数组的形状完全相同。
- 数组具有相同的维度数量,每个维度的长度可以是常用长度或1。
- 尺寸太小的阵列可能会将其形状预先设置为长度为1的维度,以使上述属性为真。
以下程序显示了广播示例。
例2
import numpy as np 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]) print 'First array:' print a print '\n' print 'Second array:' print b print '\n' print 'First Array + Second Array' print a + b
该程序的输出如下 –
First array: [[ 0. 0. 0.] [ 10. 10. 10.] [ 20. 20. 20.] [ 30. 30. 30.]] Second array: [ 1. 2. 3.] First Array + Second Array [[ 1. 2. 3.] [ 11. 12. 13.] [ 21. 22. 23.] [ 31. 32. 33.]]
下图演示了阵列b如何广播以与a兼容。
NumPy 遍历数组
NumPy包中包含一个迭代器对象numpy.nditer。 它是一个有效的多维迭代器对象,可以用它迭代数组。 使用Python的标准Iterator接口访问数组的每个元素。
让我们使用arange()函数创建一个3X4数组,并使用nditer对其进行迭代。
例1
import numpy as np a = np.arange(0,60,5) a = a.reshape(3,4) print 'Original array is:' print a print '\n' print 'Modified array is:' for x in np.nditer(a): print x,
这个程序的输出如下 –
Original array is: [[ 0 5 10 15] [20 25 30 35] [40 45 50 55]] Modified array is: 0 5 10 15 20 25 30 35 40 45 50 55
例2
迭代顺序选择为匹配数组的内存布局,而不考虑特定的顺序。 这可以通过迭代上述数组的转置来看到。
import numpy as np a = np.arange(0,60,5) a = a.reshape(3,4) print 'Original array is:' print a print '\n' print 'Transpose of the original array is:' b = a.T print b print '\n' print 'Modified array is:' for x in np.nditer(b): print x,
这个程序的输出如下 –
Original array is: [[ 0 5 10 15] [20 25 30 35] [40 45 50 55]] Transpose of the original array is: [[ 0 20 40] [ 5 25 45] [10 30 50] [15 35 55]] Modified array is: 0 5 10 15 20 25 30 35 40 45 50 55
迭代次序
如果使用F样式顺序存储相同的元素,则迭代器会选择更有效的方式遍历数组。
例1
import numpy as np a = np.arange(0,60,5) a = a.reshape(3,4) print 'Original array is:' print a print '\n' print 'Transpose of the original array is:' b = a.T print b print '\n' print 'Sorted in C-style order:' c = b.copy(order='C') print c for x in np.nditer(c): print x, print '\n' print 'Sorted in F-style order:' c = b.copy(order='F') print c for x in np.nditer(c): print x,
这个程序的输出如下 –
Original array is: [[ 0 5 10 15] [20 25 30 35] [40 45 50 55]] Transpose of the original array is: [[ 0 20 40] [ 5 25 45] [10 30 50] [15 35 55]] Sorted in C-style order: [[ 0 20 40] [ 5 25 45] [10 30 50] [15 35 55]] 0 20 40 5 25 45 10 30 50 15 35 55 Sorted in F-style order: [[ 0 20 40] [ 5 25 45] [10 30 50] [15 35 55]] 0 5 10 15 20 25 30 35 40 45 50 55
例2
可以通过明确提及nditer对象来使用特定顺序。
import numpy as np a = np.arange(0,60,5) a = a.reshape(3,4) print 'Original array is:' print a print '\n' print 'Sorted in C-style order:' for x in np.nditer(a, order = 'C'): print x, print '\n' print 'Sorted in F-style order:' for x in np.nditer(a, order = 'F'): print x,
这个程序的输出如下 –
Original array is: [[ 0 5 10 15] [20 25 30 35] [40 45 50 55]] Sorted in C-style order: 0 5 10 15 20 25 30 35 40 45 50 55 Sorted in F-style order: 0 20 40 5 25 45 10 30 50 15 35 55
修改数组值
nditer对象具有另一个可选参数,称为op_flags。 它的默认值是只读的,但可以设置为读写模式或只写模式。 这将启用使用此迭代器修改数组元素。
例子
import numpy as np a = np.arange(0,60,5) a = a.reshape(3,4) print 'Original array is:' print a print '\n' for x in np.nditer(a, op_flags=['readwrite']): x[...]=2*x print 'Modified array is:' print a
这个程序的输出如下 –
Original array is: [[ 0 5 10 15] [20 25 30 35] [40 45 50 55]] Modified array is: [[ 0 10 20 30] [ 40 50 60 70] [ 80 90 100 110]]
外部循环
nditer类的构造函数有一个’flags’参数,它可以取下列值 –
序号 | 参数 & 描述 |
---|---|
1 | c_index C_order索引 |
2 | f_index Fortran_order索引 |
3 | multi-index 可以跟踪每次迭代一次的索引类型 |
4 | external_loop 使给出的值成为具有多个值而不是零维数组的一维数组 |
例子
在以下示例中,迭代器将遍历与每列对应的一维数组。
import numpy as np a = np.arange(0,60,5) a = a.reshape(3,4) print 'Original array is:' print a print '\n' print 'Modified array is:' for x in np.nditer(a, flags = ['external_loop'], order = 'F'): print x,
这个程序的输出如下 –
Original array is: [[ 0 5 10 15] [20 25 30 35] [40 45 50 55]] Modified array is: [ 0 20 40] [ 5 25 45] [10 30 50] [15 35 55]
广播迭代
如果两个数组可以广播,则组合的nditer对象可以同时迭代它们。 假设数组a的维数为3X4,并且存在维数为1X4的另一个数组b,则使用以下类型的迭代器(数组b以广播的大小a)。
例子
import numpy as np a = np.arange(0,60,5) a = a.reshape(3,4) print 'First array is:' print a print '\n' print 'Second array is:' b = np.array([1, 2, 3, 4], dtype = int) print b print '\n' print 'Modified array is:' for x,y in np.nditer([a,b]): print "%d:%d" % (x,y),
这个程序的输出如下 –
First array is: [[ 0 5 10 15] [20 25 30 35] [40 45 50 55]] Second array is: [1 2 3 4] Modified array is: 0:1 5:2 10:3 15:4 20:1 25:2 30:3 35:4 40:1 45:2 50:3 55:4
NumPy 数组操作
NumPy包中有几个例程可用于处理ndarray对象中的元素。 它们可以分为以下几类 –
改变形状
序号 | 形状 & 描述 |
---|---|
1 | reshape 给数组赋予新的形状而不更改其数据 |
2 | flat 数组上的一维迭代器 |
3 | flatten 返回一维数组的副本 |
4 | ravel 返回一个连续的扁平数组 |
numpy.reshape
此功能在不更改数据的情况下为阵列提供新的形状。 它接受以下参数 –
numpy.reshape(arr, newshape, order')
序号 | 参数 & 描述 |
---|---|
1 | arr 数组被重构 |
2 | newshape int或int的元组。 新形状应该与原始形状兼容 |
3 | order ‘C’表示C语言风格,’F’表示Fortran风格,’A’表示如果数组存储在类似Fortran的连续内存中,则表示Fortran,否则为C风格 |
例子
import numpy as np a = np.arange(8) print 'The original array:' print a print '\n' b = a.reshape(4,2) print 'The modified array:' print b
程序输出如下-
The original array: [0 1 2 3 4 5 6 7] The modified array: [[0 1] [2 3] [4 5] [6 7]]
numpy.ndarray.flat
该函数返回数组上的一维迭代器。 它的行为与Python的内置迭代器相似。
例子
import numpy as np a = np.arange(8).reshape(2,4) print 'The original array:' print a print '\n' print 'After applying the flat function:' # returns element corresponding to index in flattened array print a.flat[5]
程序输出如下-
The original array: [[0 1 2 3] [4 5 6 7]] After applying the flat function: 5
numpy.ndarray.flatten
该函数返回一个折叠成一维的数组的副本。 该功能采用以下参数。
ndarray.flatten(order)
序号 | 参数 & 描述 |
---|---|
1 | order ‘C’行主(默认值:’F’:列主要’A’:按列主要顺序展平,如果a是Fortran在内存中连续的行,否则按行排序’K’:按元素的顺序展平a 发生在记忆中 |
例子
import numpy as np a = np.arange(8).reshape(2,4) print 'The original array is:' print a print '\n' # default is column-major print 'The flattened array is:' print a.flatten() print '\n' print 'The flattened array in F-style ordering:' print a.flatten(order = 'F')
程序输出如下-
The original array is: [[0 1 2 3] [4 5 6 7]] The flattened array is: [0 1 2 3 4 5 6 7] The flattened array in F-style ordering: [0 4 1 5 2 6 3 7]
numpy.ravel
这个函数返回一个平坦的一维数组。 只有在需要时才进行复制。 返回的数组的类型与输入数组的类型相同。 该功能需要一个参数。
numpy.ravel(a, order)
序号 | 参数 & 描述 |
---|---|
1 | order ‘C’行主(默认值:’F’:列主要’A’:按列主要顺序展平,如果a是Fortran在内存中连续的行,否则按行排序’K’:按元素的顺序展平a 发生在记忆中 |
例子
import numpy as np a = np.arange(8).reshape(2,4) print 'The original array is:' print a print '\n' print 'After applying ravel function:' print a.ravel() print '\n' print 'Applying ravel function in F-style ordering:' print a.ravel(order = 'F')
程序输出如下-
The original array is: [[0 1 2 3] [4 5 6 7]] After applying ravel function: [0 1 2 3 4 5 6 7] Applying ravel function in F-style ordering: [0 4 1 5 2 6 3 7]
转置操作
序号 | 操作 & 描述 |
---|---|
1 | transpose 置换数组的维数 |
2 | ndarray.T 同self.transpose() |
3 | rollaxis 向后滚动指定的轴 |
4 | swapaxes 交换数组的两个轴 |
transpose
此函数可以对给定数组的维度进行置换。 它尽可能返回一个视图。 该功能采用以下参数。
numpy.transpose(arr, axes)
序号 | 参数 & 描述 |
---|---|
1 | arr 该数组将被调换 |
2 | axes 输入的列表,对应于维度。 默认情况下,维度颠倒 |
例子
import numpy as np a = np.arange(12).reshape(3,4) print 'The original array is:' print a print '\n' print 'The transposed array is:' print np.transpose(a)
程序输出如下-
The original array is: [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] The transposed array is: [[ 0 4 8] [ 1 5 9] [ 2 6 10] [ 3 7 11]]
numpy.ndarray.T
这个函数属于ndarray类。 它的行为与numpy.transpose相似。
例子
import numpy as np a = np.arange(12).reshape(3,4) print 'The original array is:' print a print '\n' print 'Array after applying the function:' print a.T
程序输出如下-
The original array is: [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] Array after applying the function: [[ 0 4 8] [ 1 5 9] [ 2 6 10] [ 3 7 11]]
numpy.rollaxis
该功能向后滚动指定的轴,直到它位于指定的位置。 该功能需要三个参数。
numpy.rollaxis(arr, axis, start)
序号 | 参数 & 描述 |
---|---|
1 | arr 输入数组 |
2 | axes 轴向后滚动。 其他轴的位置相对于彼此不变 |
3 | start 默认为零,导致完整的滚动。 滚动,直到到达指定的位置 |
例子
# It creates 3 dimensional ndarray import numpy as np a = np.arange(8).reshape(2,2,2) print 'The original array:' print a print '\n' # to roll axis-2 to axis-0 (along width to along depth) print 'After applying rollaxis function:' print np.rollaxis(a,2) # to roll axis 0 to 1 (along width to height) print '\n' print 'After applying rollaxis function:' print np.rollaxis(a,2,1)
程序输出如下-
The original array: [[[0 1] [2 3]] [[4 5] [6 7]]] After applying rollaxis function: [[[0 2] [4 6]] [[1 3] [5 7]]] After applying rollaxis function: [[[0 2] [1 3]] [[4 6] [5 7]]]
numpy.swapaxes
该功能交换数组的两个轴。 对于1.10之后的NumPy版本,返回交换数组的视图。 该功能采用以下参数。
numpy.swapaxes(arr, axis1, axis2)
序号 | 参数 & 描述 |
---|---|
1 | arr 输入数组,其轴要交换 |
2 | axis1 int值对应第一个轴 |
3 | axis2 int值对应第二个轴 |
例子
# It creates a 3 dimensional ndarray import numpy as np a = np.arange(8).reshape(2,2,2) print 'The original array:' print a print '\n' # now swap numbers between axis 0 (along depth) and axis 2 (along width) print 'The array after applying the swapaxes function:' print np.swapaxes(a, 2, 0)
程序输出如下-
The original array: [[[0 1] [2 3]] [[4 5] [6 7]]] The array after applying the swapaxes function: [[[0 4] [2 6]] [[1 5] [3 7]]]
更改维度
序号 | 维度 & 描述 |
---|---|
1 | broadcast 产生一个模仿广播的对象 |
2 | broadcast_to 将数组广播到新的形状 |
3 | expand_dims 扩展数组的形状 |
4 | squeeze 从数组形状中移除一维条目 |
numpy.broadcast
如前所述,NumPy已经内置了对广播的支持。 此功能模仿广播机制。 它返回一个封装一个数组与另一个数组的广播结果的对象。
该函数将两个数组作为输入参数。 以下示例说明了它的用法。
例子
import numpy as np x = np.array([[1], [2], [3]]) y = np.array([4, 5, 6]) # tobroadcast x against y b = np.broadcast(x,y) # it has an iterator property, a tuple of iterators along self's "components." print 'Broadcast x against y:' r,c = b.iters print r.next(), c.next() print r.next(), c.next() print '\n' # shape attribute returns the shape of broadcast object print 'The shape of the broadcast object:' print b.shape print '\n' # to add x and y manually using broadcast b = np.broadcast(x,y) c = np.empty(b.shape) print 'Add x and y manually using broadcast:' print c.shape print '\n' c.flat = [u + v for (u,v) in b] print 'After applying the flat function:' print c print '\n' # same result obtained by NumPy's built-in broadcasting support print 'The summation of x and y:' print x + y
程序输出如下-
Broadcast x against y: 1 4 1 5 The shape of the broadcast object: (3, 3) Add x and y manually using broadcast: (3, 3) After applying the flat function: [[ 5. 6. 7.] [ 6. 7. 8.] [ 7. 8. 9.]] The summation of x and y: [[5 6 7] [6 7 8] [7 8 9]]
numpy.broadcast_to
该函数将数组广播到新的形状。 它在原始数组上返回一个只读视图。 它通常不是连续的。 如果新形状不符合NumPy的广播规则,该函数可能会抛出ValueError。
注 – 此功能可用于1.10.0及更高版本。
numpy.broadcast_to(array, shape, subok)
例子
import numpy as np a = np.arange(4).reshape(1,4) print 'The original array:' print a print '\n' print 'After applying the broadcast_to function:' print np.broadcast_to(a,(4,4))
程序输出如下-
[[0 1 2 3] [0 1 2 3] [0 1 2 3] [0 1 2 3]]
numpy.expand_dims
该功能通过在指定位置插入新轴来扩展数组。 该功能需要两个参数。
numpy.expand_dims(arr, axis)
序号 | 参数 & 描述 |
---|---|
1 | arr 输入数组 |
2 | axis 要插入在新轴的位置 |
例子
import numpy as np x = np.array(([1,2],[3,4])) print 'Array x:' print x print '\n' y = np.expand_dims(x, axis = 0) print 'Array y:' print y print '\n' print 'The shape of X and Y array:' print x.shape, y.shape print '\n' # insert axis at position 1 y = np.expand_dims(x, axis = 1) print 'Array Y after inserting axis at position 1:' print y print '\n' print 'x.ndim and y.ndim:' print x.ndim,y.ndim print '\n' print 'x.shape and y.shape:' print x.shape, y.shape
程序输出如下-
Array x: [[1 2] [3 4]] Array y: [[[1 2] [3 4]]] The shape of X and Y array: (2, 2) (1, 2, 2) Array Y after inserting axis at position 1: [[[1 2]] [[3 4]]] x.ndim and y.ndim: 2 3 x.shape and y.shape: (2, 2) (2, 1, 2)
numpy.squeeze
该函数从给定数组的形状中移除一维条目。 该功能需要两个参数。
numpy.squeeze(arr, axis)
序号 | 参数 & 描述 |
---|---|
1 | arr 输入数组 |
2 | axis int或int的元组。 选择形状中的单个维条目的子集 |
例子
import numpy as np x = np.arange(9).reshape(1,3,3) print 'Array X:' print x print '\n' y = np.squeeze(x) print 'Array Y:' print y print '\n' print 'The shapes of X and Y array:' print x.shape, y.shape
程序输出如下-
Array X: [[[0 1 2] [3 4 5] [6 7 8]]] Array Y: [[0 1 2] [3 4 5] [6 7 8]] The shapes of X and Y array: (1, 3, 3) (3, 3)
加入数组
序号 | 数组 & 描述 |
---|---|
1 | concatenate 沿着现有轴加入一系列数组 |
2 | stack 沿着一个新的轴加入一系列数组 |
3 | hstack 按水平顺序堆叠数组(按列) |
4 | vstack 按垂直顺序堆叠数组(按行) |
numpy.concatenate
连接是指加入。 该函数用于沿指定的轴连接两个或多个相同形状的数组。 该功能采用以下参数。
numpy.concatenate((a1, a2, ...), axis)
序号 | 参数 & 描述 |
---|---|
1 | a1,a2.. 相同类型的数组的序列 |
2 | axis 必须连接数组的轴。 缺省值是0 |
例子
import numpy as np a = np.array([[1,2],[3,4]]) print 'First array:' print a print '\n' b = np.array([[5,6],[7,8]]) print 'Second array:' print b print '\n' # both the arrays are of same dimensions print 'Joining the two arrays along axis 0:' print np.concatenate((a,b)) print '\n' print 'Joining the two arrays along axis 1:' print np.concatenate((a,b),axis = 1)
程序输出如下-
First array: [[1 2] [3 4]] Second array: [[5 6] [7 8]] Joining the two arrays along axis 0: [[1 2] [3 4] [5 6] [7 8]] Joining the two arrays along axis 1: [[1 2 5 6] [3 4 7 8]]
numpy.stack
这个函数沿着一个新的轴加入数组序列。 自NumPy版本1.10.0开始,此功能已添加。 需要提供以下参数。
注 – 此功能在版本1.10.0及更高版本中可用。
numpy.stack(arrays, axis)
序号 | 参数 & 描述 |
---|---|
1 | arrays 输相同形状的数组序列 |
2 | axis 输入数组沿其堆叠的结果数组中的轴 |
例子
import numpy as np a = np.array([[1,2],[3,4]]) print 'First Array:' print a print '\n' b = np.array([[5,6],[7,8]]) print 'Second Array:' print b print '\n' print 'Stack the two arrays along axis 0:' print np.stack((a,b),0) print '\n' print 'Stack the two arrays along axis 1:' print np.stack((a,b),1)
程序输出如下-
First array: [[1 2] [3 4]] Second array: [[5 6] [7 8]] Stack the two arrays along axis 0: [[[1 2] [3 4]] [[5 6] [7 8]]] Stack the two arrays along axis 1: [[[1 2] [5 6]] [[3 4] [7 8]]]
numpy.hstack
numpy.stack函数的变体进行堆栈以便水平地制作单个数组。
例子
import numpy as np a = np.array([[1,2],[3,4]]) print 'First array:' print a print '\n' b = np.array([[5,6],[7,8]]) print 'Second array:' print b print '\n' print 'Horizontal stacking:' c = np.hstack((a,b)) print c print '\n'
程序输出如下-
First array: [[1 2] [3 4]] Second array: [[5 6] [7 8]] Horizontal stacking: [[1 2 5 6] [3 4 7 8]]
numpy.vstack
numpy.stack函数的变体进行堆栈以垂直地创建单个数组。
例子
import numpy as np a = np.array([[1,2],[3,4]]) print 'First array:' print a print '\n' b = np.array([[5,6],[7,8]]) print 'Second array:' print b print '\n' print 'Vertical stacking:' c = np.vstack((a,b)) print c
程序输出如下-
First array: [[1 2] [3 4]] Second array: [[5 6] [7 8]] Vertical stacking: [[1 2] [3 4] [5 6] [7 8]]
分裂阵列
序号 | 数组 & 描述 |
---|---|
1 | split 将数组拆分成多个子数组 |
2 | hsplit 将数组水平分割成多个子数组(按列) |
3 | vsplit 将数组垂直分割成多个子数组(按行) |
numpy.split
该函数将数组沿着指定的轴分成子阵列。 该功能需要三个参数。
numpy.split(ary, indices_or_sections, axis)
序号 | 参数 & 描述 |
---|---|
1 | ary 输入数组,将被拆分 |
2 | indices_or_sections 可以是一个整数,表示要从输入数组创建的相等大小的子数组的数量。 如果此参数是一维数组,则这些条目将指示要创建新子数组的点。 |
3 | axis 默认值是0 |
例子
import numpy as np a = np.arange(9) print 'First array:' print a print '\n' print 'Split the array in 3 equal-sized subarrays:' b = np.split(a,3) print b print '\n' print 'Split the array at positions indicated in 1-D array:' b = np.split(a,[4,7]) print b
程序输出如下-
First array: [0 1 2 3 4 5 6 7 8] Split the array in 3 equal-sized subarrays: [array([0, 1, 2]), array([3, 4, 5]), array([6, 7, 8])] Split the array at positions indicated in 1-D array: [array([0, 1, 2, 3]), array([4, 5, 6]), array([7, 8])]
numpy.hsplit
numpy.hsplit是split()函数的一个特例,其中axis是1,表示水平分割,与输入数组的维度无关。
例子
import numpy as np a = np.arange(16).reshape(4,4) print 'First array:' print a print '\n' print 'Horizontal splitting:' b = np.hsplit(a,2) print b print '\n'
程序输出如下-
First array: [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11] [12 13 14 15]] Horizontal splitting: [array([[ 0, 1], [ 4, 5], [ 8, 9], [12, 13]]), array([[ 2, 3], [ 6, 7], [10, 11], [14, 15]])]
numpy.vsplit
numpy.vsplit是split()函数的一个特例,其中axis是1,表示纵向分割,而不管输入数组的维度如何。 以下示例说明了这一点。
例子
import numpy as np a = np.arange(16).reshape(4,4) print 'First array:' print a print '\n' print 'Vertical splitting:' b = np.vsplit(a,2) print b
程序输出如下-
First array: [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11] [12 13 14 15]] Vertical splitting: [array([[0, 1, 2, 3], [4, 5, 6, 7]]), array([[ 8, 9, 10, 11], [12, 13, 14, 15]])]
添加/删除元素
序号 | 元素 & 描述 |
---|---|
1 | resize 返回具有指定形状的新数组 |
2 | append 将值附加到数组的末尾 |
3 | insert 在给定索引之前沿给定轴插入值 |
4 | delete 返回一个新数组,其中沿着一个轴的子数组被删除 |
5 | unique 查找数组的特定元素 |
numpy.resize
该函数返回一个具有指定大小的新数组。 如果新维度大于原件维度,则包含原件中重复的条目副本。 该功能采用以下参数。
numpy.resize(arr, shape)
序号 | 参数 & 描述 |
---|---|
1 | arr 输入要调整大小的数组 |
2 | shape 结果数组的新形状 |
例子
import numpy as np a = np.array([[1,2,3],[4,5,6]]) print 'First array:' print a print '\n' print 'The shape of first array:' print a.shape print '\n' b = np.resize(a, (3,2)) print 'Second array:' print b print '\n' print 'The shape of second array:' print b.shape print '\n' # Observe that first row of a is repeated in b since size is bigger print 'Resize the second array:' b = np.resize(a,(3,3)) print b
程序输出如下-
First array: [[1 2 3] [4 5 6]] The shape of first array: (2, 3) Second array: [[1 2] [3 4] [5 6]] The shape of second array: (3, 2) Resize the second array: [[1 2 3] [4 5 6] [1 2 3]]
numpy.append
该函数在输入数组的末尾添加值。 追加操作不在位,分配一个新的数组。 此外,输入数组的维度必须匹配,否则会生成ValueError。
numpy.append(arr, values, axis)
序号 | 参数 & 描述 |
---|---|
1 | arr 输入数组 |
2 | values 附加到arr。 它的形状必须与arr相同(不包括附加轴) |
3 | axis 追加操作所沿的轴。 如果没有给出,则两个参数都是平坦的 |
例子
import numpy as np a = np.array([[1,2,3],[4,5,6]]) print 'First array:' print a print '\n' print 'Append elements to array:' print np.append(a, [7,8,9]) print '\n' print 'Append elements along axis 0:' print np.append(a, [[7,8,9]],axis = 0) print '\n' print 'Append elements along axis 1:' print np.append(a, [[5,5,5],[7,8,9]],axis = 1)
程序输出如下-
First array: [[1 2 3] [4 5 6]] Append elements to array: [1 2 3 4 5 6 7 8 9] Append elements along axis 0: [[1 2 3] [4 5 6] [7 8 9]] Append elements along axis 1: [[1 2 3 5 5 5] [4 5 6 7 8 9]]
numpy.insert
此函数将值插入输入数组中沿给定轴和给定索引之前。 如果将值的类型转换为插入,则它与输入数组不同。 插入没有完成,函数返回一个新的数组。 另外,如果没有提到轴,则输入数组变平。
numpy.insert(arr, obj, values, axis)
序号 | 参数 & 描述 |
---|---|
1 | arr 输入数组 |
2 | obj 插入之前的索引/td> |
3 | values 要插入的值的数组 |
4 | axis 插入的轴线。 如果没有给出,输入数组变平 |
例子
import numpy as np a = np.array([[1,2],[3,4],[5,6]]) print 'First array:' print a print '\n' print 'Axis parameter not passed. The input array is flattened before insertion.' print np.insert(a,3,[11,12]) print '\n' print 'Axis parameter passed. The values array is broadcast to match input array.' print 'Broadcast along axis 0:' print np.insert(a,1,[11],axis = 0) print '\n' print 'Broadcast along axis 1:' print np.insert(a,1,11,axis = 1)
程序输出如下-
First array: [[1 2] [3 4] [5 6]] Axis parameter not passed. The input array is flattened before insertion. [ 1 2 3 11 12 4 5 6] Axis parameter passed. The values array is broadcast to match input array. Broadcast along axis 0: [[ 1 2] [11 11] [ 3 4] [ 5 6]] Broadcast along axis 1: [[ 1 11 2] [ 3 11 4] [ 5 11 6]]
numpy.delete
该函数返回一个新的数组,其中从输入数组中删除指定的子数组。 与insert()函数一样,如果不使用axis参数,则输入数组将变平。 该功能采用以下参数 –
Numpy.delete(arr, obj, axis)
序号 | 参数 & 描述 |
---|---|
1 | arr 输入数组 |
2 | obj 可以是切片,整数或整数数组,指示要从输入数组中删除的子数组 |
3 | axis 删除给定子数组的轴。 如果没有给出,arr是扁平的 |
例子
import numpy as np a = np.arange(12).reshape(3,4) print 'First array:' print a print '\n' print 'Array flattened before delete operation as axis not used:' print np.delete(a,5) print '\n' print 'Column 2 deleted:' print np.delete(a,1,axis = 1) print '\n' print 'A slice containing alternate values from array deleted:' a = np.array([1,2,3,4,5,6,7,8,9,10]) print np.delete(a, np.s_[::2])
程序输出如下-
First array: [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] Array flattened before delete operation as axis not used: [ 0 1 2 3 4 6 7 8 9 10 11] Column 2 deleted: [[ 0 2 3] [ 4 6 7] [ 8 10 11]] A slice containing alternate values from array deleted: [ 2 4 6 8 10]
numpy.unique
该函数返回输入数组中唯一元素的数组。 该函数可以返回唯一的vales数组和相关索引数组的元组。 索引的性质取决于函数调用中返回参数的类型。
numpy.unique(arr, return_index, return_inverse, return_counts)
序号 | 参数 & 描述 |
---|---|
1 | arr 输入数组,如果不是一维阵列,将会变平 |
2 | return_index 如果为True,则返回输入数组中元素的索引 |
3 | return_inverse 如果为True,则返回唯一数组的索引,该数组可用于重构输入数组 |
4 | return_counts 如果为True,则返回唯一数组中元素出现在原始数组中的次数 |
例子
import numpy as np a = np.array([5,2,6,2,7,5,6,8,2,9]) print 'First array:' print a print '\n' print 'Unique values of first array:' u = np.unique(a) print u print '\n' print 'Unique array and Indices array:' u,indices = np.unique(a, return_index = True) print indices print '\n' print 'We can see each number corresponds to index in original array:' print a print '\n' print 'Indices of unique array:' u,indices = np.unique(a,return_inverse = True) print u print '\n' print 'Indices are:' print indices print '\n' print 'Reconstruct the original array using indices:' print u[indices] print '\n' print 'Return the count of repetitions of unique elements:' u,indices = np.unique(a,return_counts = True) print u print indices
程序输出如下-
First array: [5 2 6 2 7 5 6 8 2 9] Unique values of first array: [2 5 6 7 8 9] Unique array and Indices array: [1 0 2 4 7 9] We can see each number corresponds to index in original array: [5 2 6 2 7 5 6 8 2 9] Indices of unique array: [2 5 6 7 8 9] Indices are: [1 0 2 0 3 1 2 4 0 5] Reconstruct the original array using indices: [5 2 6 2 7 5 6 8 2 9] Return the count of repetitions of unique elements: [2 5 6 7 8 9] [3 2 2 1 1 1]
NumPy 位运算符
以下是NumPy包中可用的按位运算功能。
序号 | 操作 & 描述 |
---|---|
1 | bitwise_and 计算数组元素的按位与操作 |
2 | bitwise_or 计算数组元素的按位或运算 |
3 | invert 计算按位NOT |
4 | left_shift 将二进制表示的位向左移位 |
5 | right_shift 将二进制表示的位向右移位 |
NumPy – bitwise_and
输入数组中整数的二进制表示的相应位上的按位“与”操作由np.bitwise_and()函数计算。
例子
import numpy as np print 'Binary equivalents of 13 and 17:' a,b = 13,17 print bin(a), bin(b) print '\n' print 'Bitwise AND of 13 and 17:' print np.bitwise_and(13, 17)
程序输出如下-
Binary equivalents of 13 and 17: 0b1101 0b10001 Bitwise AND of 13 and 17: 1
NumPy – bitwise_or
输入数组中整数的二进制表示的相应位上的按位或运算由np.bitwise_or()函数计算。
例子
import numpy as np a,b = 13,17 print 'Binary equivalents of 13 and 17:' print bin(a), bin(b) print 'Bitwise OR of 13 and 17:' print np.bitwise_or(13, 17)
程序输出如下-
Binary equivalents of 13 and 17: 0b1101 0b10001 Bitwise OR of 13 and 17: 29
numpy.invert()
该函数计算输入数组中整数的按位NOT结果。 对于有符号整数,返回2的补码。
例子
import numpy as np print 'Invert of 13 where dtype of ndarray is uint8:' print np.invert(np.array([13], dtype = np.uint8)) print '\n' # Comparing binary representation of 13 and 242, we find the inversion of bits print 'Binary representation of 13:' print np.binary_repr(13, width = 8) print '\n' print 'Binary representation of 242:' print np.binary_repr(242, width = 8)
程序输出如下-
Invert of 13 where dtype of ndarray is uint8: [242] Binary representation of 13: 00001101 Binary representation of 242: 11110010
NumPy – left_shift
numpy.left_shift()函数将数组元素的二进制表示中的位移动到指定位置的左侧。 从右边追加相等数量的0。
例子
import numpy as np print 'Left shift of 10 by two positions:' print np.left_shift(10,2) print '\n' print 'Binary representation of 10:' print np.binary_repr(10, width = 8) print '\n' print 'Binary representation of 40:' print np.binary_repr(40, width = 8) # Two bits in '00001010' are shifted to left and two 0s appended from right.
程序输出如下-
Left shift of 10 by two positions: 40 Binary representation of 10: 00001010 Binary representation of 40: 00101000
NumPy – right_shift
numpy.right_shift()函数将数组元素的二进制表示中的位向右移动指定位置,并从左侧追加相同数量的0。
import numpy as np print 'Right shift 40 by two positions:' print np.right_shift(40,2) print '\n' print 'Binary representation of 40:' print np.binary_repr(40, width = 8) print '\n' print 'Binary representation of 10' print np.binary_repr(10, width = 8) # Two bits in '00001010' are shifted to right and two 0s appended from left.
程序输出如下-
Right shift 40 by two positions: 10 Binary representation of 40: 00101000 Binary representation of 10 00001010
NumPy 字符串函数
以下函数用于对dtype numpy.string_或numpy.unicode_的数组执行向量化字符串操作。 它们基于Python内置库中的标准字符串函数。
序号 | 函数 & 描述 |
---|---|
1 | add() 返回两个str或Unicode数组的元素方式字符串连接 |
2 | multiply() 返回具有多个级联的字符串 |
3 | center() 返回给定字符串的副本,其元素以指定长度的字符串为中心 |
4 | capitalize() 仅返回大写字母的第一个字符的副本 |
5 | title() 返回字符串或unicode的基于元素的标题 |
6 | lower() 转换为小写 |
7 | upper() 转换为大写 |
8 | split() 返回字符串中的单词列表 |
9 | splitlines() 返回元素中的行的列表,在行边界处突破 |
10 | strip() 返回删除前导字符和尾随字符的副本 |
11 | join() 返回序列中字符串连接的字符串 |
12 | replace()返回所有出现的子字符串被新字符串替换的字符串副本 |
13 | decode() 调用str.decode |
14 | encode() 调用str.encode |
这些函数在字符数组类(numpy.char)中定义。 较旧的Numarray软件包包含chararray类。 numpy.char类中的上述函数在执行矢量化字符串操作时非常有用。
numpy.char.add()
这个函数执行元素字符串连接。
import numpy as np print 'Concatenate two strings:' print np.char.add(['hello'],[' xyz']) print '\n' print 'Concatenation example:' print np.char.add(['hello', 'hi'],[' abc', ' xyz'])
程序输出如下-
Concatenate two strings: ['hello xyz'] Concatenation example: ['hello abc' 'hi xyz']
numpy.char.multiply()
这个函数执行多个级联。
import numpy as np print np.char.multiply('Hello ',3)
程序输出如下-
Hello Hello Hello
numpy.char.center()
此函数返回所需宽度的数组,以便输入字符串居中并用fillchar填充左侧和右侧。
import numpy as np # np.char.center(arr, width,fillchar) print np.char.center('hello', 20,fillchar = '*')
程序输出如下-
*******hello********
numpy.char.capitalize()
该函数返回大写字母的第一个字母的副本。
import numpy as np print np.char.capitalize('hello world')
程序输出如下-
Hello world
numpy.char.title()
此函数返回输入字符串的标题封装版本,其中每个单词的首字母大写。
import numpy as np print np.char.title('hello how are you?')
程序输出如下-
Hello How Are You?
numpy.char.lower()
这个函数返回一个元素转换为小写的数组。 它为每个元素调用str.lower。
import numpy as np print np.char.lower(['HELLO','WORLD']) print np.char.lower('HELLO')
程序输出如下-
['hello' 'world'] hello
numpy.char.upper()
此函数调用数组中每个元素的str.upper函数以返回大写数组元素。
import numpy as np print np.char.upper('hello') print np.char.upper(['hello','world'])
程序输出如下-
HELLO ['HELLO' 'WORLD']
numpy.char.split()
该函数返回输入字符串中的单词列表。 默认情况下,使用空格作为分隔符。 否则,使用指定的分隔符来溢出字符串。
import numpy as np print np.char.split ('hello how are you?') print np.char.split ('TutorialsPoint,Hyderabad,Telangana', sep = ',')
程序输出如下-
['hello', 'how', 'are', 'you?'] ['TutorialsPoint', 'Hyderabad', 'Telangana']
numpy.char.splitlines()
该函数返回数组中元素的列表,并在行边界处突破。
import numpy as np print np.char.splitlines('hello\nhow are you?') print np.char.splitlines('hello\rhow are you?')
程序输出如下-
['hello', 'how are you?'] ['hello', 'how are you?']
numpy.char.strip()
此函数返回一个数组的副本,其中的元素被剥夺了指定字符的前导和/或尾随。
import numpy as np print np.char.strip('ashok arora','a') print np.char.strip(['arora','admin','java'],'a')
程序输出如下-
shok aror ['ror' 'dmin' 'jav']
numpy.char.join()
此方法返回一个字符串,其中各个字符通过指定的分隔符连接。
import numpy as np print np.char.join(':','dmy') print np.char.join([':','-'],['dmy','ymd'])
程序输出如下-
d:m:y ['d:m:y' 'y-m-d']
numpy.char.replace()
此函数返回输入字符串的新副本,其中所有出现的字符序列都被另一个给定序列替换。
import numpy as np print np.char.replace ('He is a good boy', 'is', 'was')
程序输出如下-
He was a good boy
numpy.char.decode()
该函数调用numpy.char.decode()使用指定的编解码器解码给定的字符串。
import numpy as np a = np.char.encode('hello', 'cp500') print a print np.char.decode(a,'cp500')
程序输出如下-
����� hello
numpy.char.encode()
该函数为数组中的每个元素调用str.encode函数。 默认编码是utf_8,可以使用标准Python库中的编解码器。
import numpy as np a = np.char.encode('hello', 'cp500') print a
程序输出如下-
�����
NumPy 数学函数
很可以理解,NumPy包含大量的各种数学运算。 NumPy提供标准的三角函数,用于算术运算的函数,处理复数的函数等。
三角函数
NumPy具有标准的三角函数,可以以弧度返回给定角度的三角比。
import numpy as np a = np.array([0,30,45,60,90]) print 'Sine of different angles:' # Convert to radians by multiplying with pi/180 print np.sin(a*np.pi/180) print '\n' print 'Cosine values for angles in array:' print np.cos(a*np.pi/180) print '\n' print 'Tangent values for given angles:' print np.tan(a*np.pi/180)
程序输出为-
Sine of different angles: [ 0. 0.5 0.70710678 0.8660254 1. ] Cosine values for angles in array: [ 1.00000000e+00 8.66025404e-01 7.07106781e-01 5.00000000e-01 6.12323400e-17] Tangent values for given angles: [ 0.00000000e+00 5.77350269e-01 1.00000000e+00 1.73205081e+00 1.63312394e+16]
arcsin,arcos和arctan函数返回给定角度的sin,cos和tan的三角函数的倒数。 这些函数的结果可以通过numpy.degrees()函数通过将弧度转换为度来验证。
import numpy as np a = np.array([0,30,45,60,90]) print 'Array containing sine values:' sin = np.sin(a*np.pi/180) print sin print '\n' print 'Compute sine inverse of angles. Returned values are in radians.' inv = np.arcsin(sin) print inv print '\n' print 'Check result by converting to degrees:' print np.degrees(inv) print '\n' print 'arccos and arctan functions behave similarly:' cos = np.cos(a*np.pi/180) print cos print '\n' print 'Inverse of cos:' inv = np.arccos(cos) print inv print '\n' print 'In degrees:' print np.degrees(inv) print '\n' print 'Tan function:' tan = np.tan(a*np.pi/180) print tan print '\n' print 'Inverse of tan:' inv = np.arctan(tan) print inv print '\n' print 'In degrees:' print np.degrees(inv)
程序输出为-
Array containing sine values: [ 0. 0.5 0.70710678 0.8660254 1. ] Compute sine inverse of angles. Returned values are in radians. [ 0. 0.52359878 0.78539816 1.04719755 1.57079633] Check result by converting to degrees: [ 0. 30. 45. 60. 90.] arccos and arctan functions behave similarly: [ 1.00000000e+00 8.66025404e-01 7.07106781e-01 5.00000000e-01 6.12323400e-17] Inverse of cos: [ 0. 0.52359878 0.78539816 1.04719755 1.57079633] In degrees: [ 0. 30. 45. 60. 90.] Tan function: [ 0.00000000e+00 5.77350269e-01 1.00000000e+00 1.73205081e+00 1.63312394e+16] Inverse of tan: [ 0. 0.52359878 0.78539816 1.04719755 1.57079633] In degrees: [ 0. 30. 45. 60. 90.]
四舍五入的功能
numpy.around()
这是一个返回四舍五入到所需精度的函数。 该功能采用以下参数。
numpy.around(a,decimals)
序号 | 参数 & 描述 |
---|---|
1 | a 输入数据 |
2 | decimals 要舍入的小数位数。 默认值为0.如果为负值,则将整数舍入到位于小数点左侧的位置 |
import numpy as np a = np.array([1.0,5.55, 123, 0.567, 25.532]) print 'Original array:' print a print '\n' print 'After rounding:' print np.around(a) print np.around(a, decimals = 1) print np.around(a, decimals = -1)
程序输出为-
Original array: [ 1. 5.55 123. 0.567 25.532] After rounding: [ 1. 6. 123. 1. 26. ] [ 1. 5.6 123. 0.6 25.5] [ 0. 10. 120. 0. 30. ]
numpy.floor()
该函数返回不大于输入参数的最大整数。 标量x的底部是最大的整数i,使得i <= x。
import numpy as np a = np.array([-1.7, 1.5, -0.2, 0.6, 10]) print 'The given array:' print a print '\n' print 'The modified array:' print np.floor(a)
程序输出为-
The given array: [ -1.7 1.5 -0.2 0.6 10. ] The modified array: [ -2. 1. -1. 0. 10.]
numpy.ceil()
ceil()函数返回输入值的上限,即标量x的最小值是最小的整数i,使得i> = x。
import numpy as np a = np.array([-1.7, 1.5, -0.2, 0.6, 10]) print 'The given array:' print a print '\n' print 'The modified array:' print np.ceil(a)
程序输出为-
The given array: [ -1.7 1.5 -0.2 0.6 10. ] The modified array: [ -1. 2. -0. 1. 10.]
NumPy 算术运算符
用于执行诸如add(),subtract(),multiply()和divide()等算术运算的输入数组必须是相同的形状,或者应符合数组广播规则。
import numpy as np a = np.arange(9, dtype = np.float_).reshape(3,3) print 'First array:' print a print '\n' print 'Second array:' b = np.array([10,10,10]) print b print '\n' print 'Add the two arrays:' print np.add(a,b) print '\n' print 'Subtract the two arrays:' print np.subtract(a,b) print '\n' print 'Multiply the two arrays:' print np.multiply(a,b) print '\n' print 'Divide the two arrays:' print np.divide(a,b)
它会产生以下输出 –
First array: [[ 0. 1. 2.] [ 3. 4. 5.] [ 6. 7. 8.]] Second array: [10 10 10] Add the two arrays: [[ 10. 11. 12.] [ 13. 14. 15.] [ 16. 17. 18.]] Subtract the two arrays: [[-10. -9. -8.] [ -7. -6. -5.] [ -4. -3. -2.]] Multiply the two arrays: [[ 0. 10. 20.] [ 30. 40. 50.] [ 60. 70. 80.]] Divide the two arrays: [[ 0. 0.1 0.2] [ 0.3 0.4 0.5] [ 0.6 0.7 0.8]]
现在让我们来讨论一下NumPy中可用的其他一些重要的算术函数。
numpy.reciprocal()
这个函数返回参数的倒数。 对于绝对值大于1的元素,由于Python处理整数除法的方式,结果始终为0。 对于整数0,发出溢出警告。
import numpy as np a = np.array([0.25, 1.33, 1, 0, 100]) print 'Our array is:' print a print '\n' print 'After applying reciprocal function:' print np.reciprocal(a) print '\n' b = np.array([100], dtype = int) print 'The second array is:' print b print '\n' print 'After applying reciprocal function:' print np.reciprocal(b)
它会产生以下输出 –
Our array is: [ 0.25 1.33 1. 0. 100. ] After applying reciprocal function: main.py:9: RuntimeWarning: divide by zero encountered in reciprocal print np.reciprocal(a) [ 4. 0.7518797 1. inf 0.01 ] The second array is: [100] After applying reciprocal function: [0]
numpy.power()
该函数将第一个输入数组中的元素作为基础处理,并将其返回为第二个输入数组中相应元素的权力。
import numpy as np a = np.array([10,100,1000]) print 'Our array is:' print a print '\n' print 'Applying power function:' print np.power(a,2) print '\n' print 'Second array:' b = np.array([1,2,3]) print b print '\n' print 'Applying power function again:' print np.power(a,b)
它会产生以下输出 –
Our array is: [ 10 100 1000] Applying power function: [ 100 10000 1000000] Second array: [1 2 3] Applying power function again: [ 10 10000 1000000000]
numpy.mod()
该函数返回输入数组中相应元素的除法余数。 函数numpy.remainder()也会产生相同的结果。
import numpy as np a = np.array([10,20,30]) b = np.array([3,5,7]) print 'First array:' print a print '\n' print 'Second array:' print b print '\n' print 'Applying mod() function:' print np.mod(a,b) print '\n' print 'Applying remainder() function:' print np.remainder(a,b)
它会产生以下输出 –
First array: [10 20 30] Second array: [3 5 7] Applying mod() function: [1 0 2] Applying remainder() function: [1 0 2]
以下函数用于对具有复数的数组执行操作。
- numpy.real() – 返回复杂数据类型参数的实部。
- numpy.imag() – 返回复数数据类型参数的虚部。
- numpy.conj() – 返回通过改变虚部符号得到的复共轭。
- numpy.angle() – 返回复杂参数的角度。 该功能具有度数参数。 如果为true,则返回角度,否则角度以弧度表示。
import numpy as np a = np.array([-5.6j, 0.2j, 11. , 1+1j]) print 'Our array is:' print a print '\n' print 'Applying real() function:' print np.real(a) print '\n' print 'Applying imag() function:' print np.imag(a) print '\n' print 'Applying conj() function:' print np.conj(a) print '\n' print 'Applying angle() function:' print np.angle(a) print '\n' print 'Applying angle() function again (result in degrees)' print np.angle(a, deg = True)
它会产生以下输出 –
Our array is: [ 0.-5.6j 0.+0.2j 11.+0.j 1.+1.j ] Applying real() function: [ 0. 0. 11. 1.] Applying imag() function: [-5.6 0.2 0. 1. ] Applying conj() function: [ 0.+5.6j 0.-0.2j 11.-0.j 1.-1.j ] Applying angle() function: [-1.57079633 1.57079633 0. 0.78539816] Applying angle() function again (result in degrees) [-90. 90. 0. 45.]
NumPy 统计函数
NumPy具有相当多的有用的统计函数,用于从数组中的给定元素中找出最小值,最大值,百分位标准偏差和方差等。 功能解释如下 –
numpy.amin() and numpy.amax()
这些函数返回给定数组中沿指定轴的元素的最小值和最大值。
import numpy as np a = np.array([[3,7,5],[8,4,3],[2,4,9]]) print 'Our array is:' print a print '\n' print 'Applying amin() function:' print np.amin(a,1) print '\n' print 'Applying amin() function again:' print np.amin(a,0) print '\n' print 'Applying amax() function:' print np.amax(a) print '\n' print 'Applying amax() function again:' print np.amax(a, axis = 0)
它会产生以下输出 –
Our array is: [[3 7 5] [8 4 3] [2 4 9]] Applying amin() function: [3 3 2] Applying amin() function again: [2 4 3] Applying amax() function: 9 Applying amax() function again: [8 7 9]
numpy.ptp()
numpy.ptp()函数返回沿轴的值范围(最大值 – 最小值)。
import numpy as np a = np.array([[3,7,5],[8,4,3],[2,4,9]]) print 'Our array is:' print a print '\n' print 'Applying ptp() function:' print np.ptp(a) print '\n' print 'Applying ptp() function along axis 1:' print np.ptp(a, axis = 1) print '\n' print 'Applying ptp() function along axis 0:' print np.ptp(a, axis = 0)
它会产生以下输出 –
Our array is: [[3 7 5] [8 4 3] [2 4 9]] Applying ptp() function: 7 Applying ptp() function along axis 1: [4 5 7] Applying ptp() function along axis 0: [6 3 6]
numpy.percentile()
百分位数(或百分位数)是统计数据中使用的度量,表示一组观测值中给定百分比的观测值下降的值。 函数numpy.percentile()采用以下参数。
numpy.percentile(a, q, axis)
序号 | 参数 & 描述 |
---|---|
1 | a 输入数组 |
2 | q 计算的百分位数必须在0-100之间 |
3 | axis 要计算百分位数的轴 |
import numpy as np a = np.array([[30,40,70],[80,20,10],[50,90,60]]) print 'Our array is:' print a print '\n' print 'Applying percentile() function:' print np.percentile(a,50) print '\n' print 'Applying percentile() function along axis 1:' print np.percentile(a,50, axis = 1) print '\n' print 'Applying percentile() function along axis 0:' print np.percentile(a,50, axis = 0)
它会产生以下输出 –
Our array is: [[30 40 70] [80 20 10] [50 90 60]] Applying percentile() function: 50.0 Applying percentile() function along axis 1: [ 40. 20. 60.] Applying percentile() function along axis 0: [ 50. 40. 60.]
numpy.median()
中位数被定义为将数据样本的高半部分与下半部分分开的值。 使用numpy.median()函数,如下面的程序所示。
import numpy as np a = np.array([[30,65,70],[80,95,10],[50,90,60]]) print 'Our array is:' print a print '\n' print 'Applying median() function:' print np.median(a) print '\n' print 'Applying median() function along axis 0:' print np.median(a, axis = 0) print '\n' print 'Applying median() function along axis 1:' print np.median(a, axis = 1)
它会产生以下输出 –
Our array is: [[30 65 70] [80 95 10] [50 90 60]] Applying median() function: 65.0 Applying median() function along axis 0: [ 50. 90. 60.] Applying median() function along axis 1: [ 65. 80. 60.]
numpy.mean()
算术平均值是沿轴的元素总和除以元素的数量。 numpy.mean()函数返回数组中元素的算术平均值。 如果提到该轴,则会沿着它进行计算。
import numpy as np a = np.array([[1,2,3],[3,4,5],[4,5,6]]) print 'Our array is:' print a print '\n' print 'Applying mean() function:' print np.mean(a) print '\n' print 'Applying mean() function along axis 0:' print np.mean(a, axis = 0) print '\n' print 'Applying mean() function along axis 1:' print np.mean(a, axis = 1)
它会产生以下输出 –
Our array is: [[1 2 3] [3 4 5] [4 5 6]] Applying mean() function: 3.66666666667 Applying mean() function along axis 0: [ 2.66666667 3.66666667 4.66666667] Applying mean() function along axis 1: [ 2. 4. 5.]
numpy.average()
加权平均数是由每个组件乘以反映其重要性的因素所产生的平均值。 numpy.average()函数根据另一个数组中给定的权重计算数组中元素的加权平均值。 该功能可以有一个轴参数。 如果没有指定轴,则数组变平。
考虑一个数组[1,2,3,4]和相应的权重[4,3,2,1],加权平均值是通过相加元素的乘积和除以权重之和得出的。
加权平均=(1 * 4 + 2 * 3 + 3 * 2 + 4 * 1)/(4 + 3 + 2 + 1)
import numpy as np a = np.array([1,2,3,4]) print 'Our array is:' print a print '\n' print 'Applying average() function:' print np.average(a) print '\n' # this is same as mean when weight is not specified wts = np.array([4,3,2,1]) print 'Applying average() function again:' print np.average(a,weights = wts) print '\n' # Returns the sum of weights, if the returned parameter is set to True. print 'Sum of weights' print np.average([1,2,3, 4],weights = [4,3,2,1], returned = True)
它会产生以下输出 –
Our array is: [1 2 3 4] Applying average() function: 2.5 Applying average() function again: 2.0 Sum of weights (2.0, 10.0)
在多维数组中,可以指定计算的轴。
import numpy as np a = np.arange(6).reshape(3,2) print 'Our array is:' print a print '\n' print 'Modified array:' wt = np.array([3,5]) print np.average(a, axis = 1, weights = wt) print '\n' print 'Modified array:' print np.average(a, axis = 1, weights = wt, returned = True)
它会产生以下输出 –
Our array is: [[0 1] [2 3] [4 5]] Modified array: [ 0.625 2.625 4.625] Modified array: (array([ 0.625, 2.625, 4.625]), array([ 8., 8., 8.]))
标准偏差
标准偏差是平均偏差平方的平方根。 标准差的公式如下 –
std = sqrt(mean(abs(x - x.mean())**2))
如果数组是[1,2,3,4],那么它的平均值是2.5。 因此,平方偏差为[2.25,0.25,0.25,2.25],其均值的平方根除以4,即sqrt(5/4)为1.1180339887498949。
import numpy as np print np.std([1,2,3,4])
它会产生以下输出 –
1.1180339887498949
方差
方差是平方偏差的平均值,即mean(abs(x – x.mean())**2)。 换句话说,标准偏差是方差的平方根。
import numpy as np print np.var([1,2,3,4])
它会产生以下输出 –
1.25
NumPy 排序,搜索和计数功能
NumPy提供了各种与分类相关的功能。 这些排序功能实现了不同的排序算法,每种排序算法都以执行速度,最差情况下的性能,所需的工作空间以及算法的稳定性为特征。 下表显示了三种排序算法的比较。
分类 | 时间复杂度 | 最坏的情况 | 空间复杂度 | 稳定性 |
---|---|---|---|---|
快速排序 | 1 | O(n^2) | 0 | no |
归并排序 | 2 | O(n*log(n)) | ~n/2 | yes |
堆排序 | 3 | O(n*log(n)) | 0 | no |
numpy.sort()
sort()函数返回输入数组的有序副本。 它有以下参数 –
numpy.sort(a, axis, kind, order)
序号 | 参数 & 描述 |
---|---|
1 | a 数组进行排序 |
2 | axis 要排序数组的轴。 如果没有,则数组将变平,并在最后一个轴上排序 |
3 | kind 默认是快速排序 |
4 | order 如果数组包含字段,则要排序字段的顺序 |
import numpy as np a = np.array([[3,7],[9,1]]) print 'Our array is:' print a print '\n' print 'Applying sort() function:' print np.sort(a) print '\n' print 'Sort along axis 0:' print np.sort(a, axis = 0) print '\n' # Order parameter in sort function dt = np.dtype([('name', 'S10'),('age', int)]) a = np.array([("raju",21),("anil",25),("ravi", 17), ("amar",27)], dtype = dt) print 'Our array is:' print a print '\n' print 'Order by name:' print np.sort(a, order = 'name')
它会产生以下输出 –
Our array is: [[3 7] [9 1]] Applying sort() function: [[3 7] [1 9]] Sort along axis 0: [[3 1] [9 7]] Our array is: [('raju', 21) ('anil', 25) ('ravi', 17) ('amar', 27)] Order by name: [('amar', 27) ('anil', 25) ('raju', 21) ('ravi', 17)]
numpy.argsort()
函数使用一系列键执行间接排序。 这些键可以看作电子表格中的一列。 该函数返回一个索引数组,使用该索引可以获取排序后的数据。 请注意,最后一个键恰好是排序的主键。
import numpy as np x = np.array([3, 1, 2]) print 'Our array is:' print x print '\n' print 'Applying argsort() to x:' y = np.argsort(x) print y print '\n' print 'Reconstruct original array in sorted order:' print x[y] print '\n' print 'Reconstruct the original array using loop:' for i in y: print x[i],
它会产生以下输出 –
Our array is: [3 1 2] Applying argsort() to x: [1 2 0] Reconstruct original array in sorted order: [1 2 3] Reconstruct the original array using loop: 1 2 3
numpy.lexsort()
函数使用一系列键执行间接排序。 这些键可以看作电子表格中的一列。 该函数返回一个索引数组,使用该索引可以获取排序后的数据。 请注意,最后一个键恰好是排序的主键。
import numpy as np nm = ('raju','anil','ravi','amar') dv = ('f.y.', 's.y.', 's.y.', 'f.y.') ind = np.lexsort((dv,nm)) print 'Applying lexsort() function:' print ind print '\n' print 'Use this index to get sorted data:' print [nm[i] + ", " + dv[i] for i in ind]
它会产生以下输出 –
Applying lexsort() function: [3 1 0 2] Use this index to get sorted data: ['amar, f.y.', 'anil, s.y.', 'raju, f.y.', 'ravi, s.y.']
NumPy模块有一些用于在数组内搜索的函数。 用于查找最大值,最小值以及满足给定条件的元素的函数是可用的。
numpy.argmax()和numpy.argmin()
这两个函数分别沿给定的轴返回最大和最小元素的索引。
import numpy as np a = np.array([[30,40,70],[80,20,10],[50,90,60]]) print 'Our array is:' print a print '\n' print 'Applying argmax() function:' print np.argmax(a) print '\n' print 'Index of maximum number in flattened array' print a.flatten() print '\n' print 'Array containing indices of maximum along axis 0:' maxindex = np.argmax(a, axis = 0) print maxindex print '\n' print 'Array containing indices of maximum along axis 1:' maxindex = np.argmax(a, axis = 1) print maxindex print '\n' print 'Applying argmin() function:' minindex = np.argmin(a) print minindex print '\n' print 'Flattened array:' print a.flatten()[minindex] print '\n' print 'Flattened array along axis 0:' minindex = np.argmin(a, axis = 0) print minindex print '\n' print 'Flattened array along axis 1:' minindex = np.argmin(a, axis = 1) print minindex
它会产生以下输出 –
Our array is: [[30 40 70] [80 20 10] [50 90 60]] Applying argmax() function: 7 Index of maximum number in flattened array [30 40 70 80 20 10 50 90 60] Array containing indices of maximum along axis 0: [1 2 0] Array containing indices of maximum along axis 1: [2 0 1] Applying argmin() function: 5 Flattened array: 10 Flattened array along axis 0: [0 1 1] Flattened array along axis 1: [0 2 0]
numpy.nonzero()
numpy.nonzero()函数返回输入数组中非零元素的索引。
import numpy as np a = np.array([[30,40,0],[0,20,10],[50,0,60]]) print 'Our array is:' print a print '\n' print 'Applying nonzero() function:' print np.nonzero (a)
它会产生以下输出 –
Our array is: [[30 40 0] [ 0 20 10] [50 0 60]] Applying nonzero() function: (array([0, 0, 1, 1, 2, 2]), array([0, 1, 1, 2, 0, 2]))
numpy.where()
where()函数返回满足给定条件的输入数组中元素的索引。
import numpy as np x = np.arange(9.).reshape(3, 3) print 'Our array is:' print x print 'Indices of elements > 3' y = np.where(x > 3) print y print 'Use these indices to get elements satisfying the condition' print x[y]
它会产生以下输出 –
Our array is: [[ 0. 1. 2.] [ 3. 4. 5.] [ 6. 7. 8.]] Indices of elements > 3 (array([1, 1, 2, 2, 2]), array([1, 2, 0, 1, 2])) Use these indices to get elements satisfying the condition [ 4. 5. 6. 7. 8.]
numpy.extract()
extract()函数返回满足任何条件的元素。
import numpy as np x = np.arange(9.).reshape(3, 3) print 'Our array is:' print x # define a condition condition = np.mod(x,2) == 0 print 'Element-wise value of condition' print condition print 'Extract elements using condition' print np.extract(condition, x)
它会产生以下输出 –
Our array is: [[ 0. 1. 2.] [ 3. 4. 5.] [ 6. 7. 8.]] Element-wise value of condition [[ True False True] [False True False] [ True False True]] Extract elements using condition [ 0. 2. 4. 6. 8.]
NumPy 字节交换
我们已经看到,存储在计算机内存中的数据取决于CPU使用的体系结构。 它可能是小端(最低有效位置存储在最小地址中)或大端(最小地址中最高有效字节)。
numpy.ndarray.byteswap()
numpy.ndarray.byteswap()函数在两个表示之间切换:bigendian和little-endian。
import numpy as np a = np.array([1, 256, 8755], dtype = np.int16) print 'Our array is:' print a print 'Representation of data in memory in hexadecimal form:' print map(hex,a) # byteswap() function swaps in place by passing True parameter print 'Applying byteswap() function:' print a.byteswap(True) print 'In hexadecimal form:' print map(hex,a) # We can see the bytes being swapped
它会产生以下输出 –
Our array is: [1 256 8755] Representation of data in memory in hexadecimal form: ['0x1', '0x100', '0x2233'] Applying byteswap() function: [256 1 13090] In hexadecimal form: ['0x100', '0x1', '0x3322']
NumPy 副本和视图
在执行函数时,其中一些返回输入数组的副本,而另一些则返回视图。 当内容物理地存储在另一个位置时,它被称为复制。 另一方面,如果提供了相同内存内容的不同视图,我们将其称为View。
没有副本
简单的赋值不会创建数组对象的副本。 相反,它使用原始数组的相同id()来访问它。 id()返回Python对象的通用标识符,类似于C中的指针。
而且,任何一方的变化都会反映在另一方面。 例如,一个变化的形状也会改变另一个的形状。
import numpy as np a = np.arange(6) print 'Our array is:' print a print 'Applying id() function:' print id(a) print 'a is assigned to b:' b = a print b print 'b has same id():' print id(b) print 'Change shape of b:' b.shape = 3,2 print b print 'Shape of a also gets changed:' print a
它会产生以下输出 –
Our array is: [0 1 2 3 4 5] Applying id() function: 139747815479536 a is assigned to b: [0 1 2 3 4 5] b has same id(): 139747815479536 Change shape of b: [[0 1] [2 3] [4 5]] Shape of a also gets changed: [[0 1] [2 3] [4 5]]
视图或浅拷贝
NumPy有ndarray.view()方法,它是一个新的数组对象,它查看原始数组的相同数据。 与之前的情况不同,新阵列的尺寸更改不会更改原始尺寸。
import numpy as np # To begin with, a is 3X2 array a = np.arange(6).reshape(3,2) print 'Array a:' print a print 'Create view of a:' b = a.view() print b print 'id() for both the arrays are different:' print 'id() of a:' print id(a) print 'id() of b:' print id(b) # Change the shape of b. It does not change the shape of a b.shape = 2,3 print 'Shape of b:' print b print 'Shape of a:' print a
它会产生以下输出 –
Array a: [[0 1] [2 3] [4 5]] Create view of a: [[0 1] [2 3] [4 5]] id() for both the arrays are different: id() of a: 140424307227264 id() of b: 140424151696288 Shape of b: [[0 1 2] [3 4 5]] Shape of a: [[0 1] [2 3] [4 5]]
数组的切片创建一个视图。
import numpy as np a = np.array([[10,10], [2,3], [4,5]]) print 'Our array is:' print a print 'Create a slice:' s = a[:, :2] print s
它会产生以下输出 –
Our array is: [[10 10] [ 2 3] [ 4 5]] Create a slice: [[10 10] [ 2 3] [ 4 5]]
深度复制
ndarray.copy()函数创建一个深度副本。 它是数组及其数据的完整副本,并不与原始数组共享。
import numpy as np a = np.array([[10,10], [2,3], [4,5]]) print 'Array a is:' print a print 'Create a deep copy of a:' b = a.copy() print 'Array b is:' print b #b does not share any memory of a print 'Can we write b is a' print b is a print 'Change the contents of b:' b[0,0] = 100 print 'Modified array b:' print b print 'a remains unchanged:' print a
它会产生以下输出 –
Array a is: [[10 10] [ 2 3] [ 4 5]] Create a deep copy of a: Array b is: [[10 10] [ 2 3] [ 4 5]] Can we write b is a False Change the contents of b: Modified array b: [[100 10] [ 2 3] [ 4 5]] a remains unchanged: [[10 10] [ 2 3] [ 4 5]]
NumPy 矩阵库
NumPy包中包含一个Matrix库numpy.matlib。 该模块具有返回矩阵而不是ndarray对象的函数。
matlib.empty()
matlib.empty()函数返回一个新的矩阵,而不初始化条目。 该功能采用以下参数。
numpy.matlib.empty(shape, dtype, order)
序号 | 参数 & 描述 |
---|---|
1 | shape int或int的元组定义新矩阵的形状 |
2 | Dtype 可选的。 输出的数据类型 |
3 | order C 或 F |
import numpy.matlib import numpy as np print np.matlib.empty((2,2)) # filled with random data
它会产生以下输出 –
[[ 2.12199579e-314, 4.24399158e-314] [ 4.24399158e-314, 2.12199579e-314]]
numpy.matlib.zeros()
该函数返回填充零的矩阵。
import numpy.matlib import numpy as np print np.matlib.zeros((2,2))
它会产生以下输出 –
[[ 0. 0.] [ 0. 0.]])
numpy.matlib.ones()
该函数返回填充1的矩阵。
import numpy.matlib import numpy as np print np.matlib.ones((2,2))
它会产生以下输出 –
[[ 1. 1.] [ 1. 1.]]
numpy.matlib.eye()
这个函数返回一个矩阵,其中对角线元素为1,其他地方为0。 该功能采用以下参数。
numpy.matlib.eye(n, M,k, dtype)
序号 | 参数 & 描述 |
---|---|
1 | n 结果矩阵中的行数 |
2 | M 列数,默认为n |
3 | k 对角线索引 |
4 | dtype 输出的数据类型 |
import numpy.matlib import numpy as np print np.matlib.eye(n = 3, M = 4, k = 0, dtype = float)
它会产生以下输出 –
[[ 1. 0. 0. 0.] [ 0. 1. 0. 0.] [ 0. 0. 1. 0.]])
numpy.matlib.identity()
numpy.matlib.identity()函数返回给定大小的标识矩阵。 单位矩阵是一个所有对角元素均为1的方阵。
import numpy.matlib import numpy as np print np.matlib.identity(5, dtype = float)
它会产生以下输出 –
[[ 1. 0. 0. 0. 0.] [ 0. 1. 0. 0. 0.] [ 0. 0. 1. 0. 0.] [ 0. 0. 0. 1. 0.] [ 0. 0. 0. 0. 1.]]
numpy.matlib.rand()
numpy.matlib.rand()函数返回填充了随机值的给定大小的矩阵。
import numpy.matlib import numpy as np print np.matlib.rand(3,3)
它会产生以下输出 –
[[ 0.82674464 0.57206837 0.15497519] [ 0.33857374 0.35742401 0.90895076] [ 0.03968467 0.13962089 0.39665201]]
请注意,矩阵总是二维的,而ndarray是一个n维数组。 两个对象都是可以相互转换的。
import numpy.matlib import numpy as np i = np.matrix('1,2;3,4') print i
它会产生以下输出 –
[[1 2] [3 4]]
import numpy.matlib import numpy as np j = np.asarray(i) print j
它会产生以下输出 –
[[1 2] [3 4]]
import numpy.matlib import numpy as np k = np.asmatrix (j) print k
它会产生以下输出 –
[[1 2] [3 4]]
NumPy 线性代数
NumPy软件包包含numpy.linalg模块,提供线性代数所需的全部功能。 下表描述了该模块中的一些重要功能。
序号 | 函数 & 描述 |
---|---|
1 | dot 两个数组的点积 |
2 | vdot 两个向量的点积 |
3 | inner 两个阵列的内积 |
4 | matmul 两个阵列的矩阵乘积 |
5 | determinant 计算数组的行列式 |
6 | solve 求解线性矩阵方程 |
7 | inv 找出矩阵的乘法逆 |
numpy.dot()
该函数返回两个数组的点积。 对于二维向量,它等价于矩阵乘法。 对于一维数组,它是矢量的内积。 对于无向数组,它是a的最后一个轴和b的倒数第二个轴的和积。
import numpy.matlib import numpy as np a = np.array([[1,2],[3,4]]) b = np.array([[11,12],[13,14]]) np.dot(a,b)
它会产生以下输出 –
[[37 40] [85 92]]
请注意,点积计算为 –
[[1*11+2*13, 1*12+2*14],[3*11+4*13, 3*12+4*14]]
numpy.vdot()
该函数返回两个向量的点积。 如果第一个参数是复数,那么它的共轭用于计算。 如果参数id是多维数组,则它变平。
import numpy as np a = np.array([[1,2],[3,4]]) b = np.array([[11,12],[13,14]]) print np.vdot(a,b)
它会产生以下输出 –
130
注 − 1*11 + 2*12 + 3*13 + 4*14 = 130
numpy.inner()
该函数返回一维数组的向量的内积。 对于更高的尺寸,它将返回最后一个轴上的和积。
import numpy as np print np.inner(np.array([1,2,3]),np.array([0,1,0])) # Equates to 1*0+2*1+3*0
它会产生以下输出 –
2
# Multi-dimensional array example import numpy as np a = np.array([[1,2], [3,4]]) print 'Array a:' print a b = np.array([[11, 12], [13, 14]]) print 'Array b:' print b print 'Inner product:' print np.inner(a,b)
它会产生以下输出 –
Array a: [[1 2] [3 4]] Array b: [[11 12] [13 14]] Inner product: [[35 41] [81 95]]
在上述情况下,内部产品计算为 –
1*11+2*12, 1*13+2*14 3*11+4*12, 3*13+4*14
numpy.matmul()
numpy.matmul()函数返回两个数组的矩阵乘积。 虽然它返回二维数组的正常乘积,但如果任一参数的维数大于2,则它将被视为位于最后两个索引中的矩阵堆栈,并相应地进行广播。
另一方面,如果其中一个参数是一维数组,则通过在它的维上附加1来将其提升为矩阵,其在乘法之后被去除。
# For 2-D array, it is matrix multiplication import numpy.matlib import numpy as np a = [[1,0],[0,1]] b = [[4,1],[2,2]] print np.matmul(a,b)
它会产生以下输出 –
[[4 1] [2 2]]
# 2-D mixed with 1-D import numpy.matlib import numpy as np a = [[1,0],[0,1]] b = [1,2] print np.matmul(a,b) print np.matmul(b,a)
它会产生以下输出 –
[1 2] [1 2]
# one array having dimensions > 2 import numpy.matlib import numpy as np a = np.arange(8).reshape(2,2,2) b = np.arange(4).reshape(2,2) print np.matmul(a,b)
它会产生以下输出 –
[[[2 3] [6 11]] [[10 19] [14 27]]]
NumPy – Determinant
行列式是线性代数中非常有用的值。 它根据方阵的对角线元素进行计算。 对于一个2×2矩阵,它仅仅是左上角和右下角元素与其他两个元素乘积的减法。
换句话说,对于矩阵[[a,b],[c,d]],行列式被计算为’ad-bc’。 较大的平方矩阵被认为是2×2矩阵的组合。
numpy.linalg.det()函数计算输入矩阵的行列式。
import numpy as np a = np.array([[1,2], [3,4]]) print np.linalg.det(a)
它会产生以下输出 –
-2.0
import numpy as np b = np.array([[6,1,1], [4, -2, 5], [2,8,7]]) print b print np.linalg.det(b) print 6*(-2*7 - 5*8) - 1*(4*7 - 5*2) + 1*(4*8 - -2*2)
它会产生以下输出 –
[[ 6 1 1] [ 4 -2 5] [ 2 8 7]] -306.0 -306
numpy.linalg.solve()
numpy.linalg.solve()函数以矩阵形式给出了线性方程组的解。
考虑以下线性方程 –
x + y + z = 6 2y + 5z = -4 2x + 5y - z = 27
它们可以用矩阵形式表示为 –
如果这三个矩阵被称为A,X和B,则方程变为 –
A*X = B Or X = A-1B
numpy.linalg.inv()
我们使用numpy.linalg.inv()函数来计算矩阵的逆。 矩阵的逆矩阵是这样的,即如果它乘以原始矩阵,它将导致单位矩阵。
import numpy as np x = np.array([[1,2],[3,4]]) y = np.linalg.inv(x) print x print y print np.dot(x,y)
它应该产生以下输出 –
[[1 2] [3 4]] [[-2. 1. ] [ 1.5 -0.5]] [[ 1.00000000e+00 1.11022302e-16] [ 0.00000000e+00 1.00000000e+00]]
现在让我们在我们的例子中创建一个矩阵A的逆。
import numpy as np a = np.array([[1,1,1],[0,2,5],[2,5,-1]]) print 'Array a:” print a ainv = np.linalg.inv(a) print 'Inverse of a:' print ainv print 'Matrix B is:' b = np.array([[6],[-4],[27]]) print b print 'Compute A-1B:' x = np.linalg.solve(a,b) print x # this is the solution to linear equations x = 5, y = 3, z = -2
它会产生以下输出 –
Array a: [[ 1 1 1] [ 0 2 5] [ 2 5 -1]] Inverse of a: [[ 1.28571429 -0.28571429 -0.14285714] [-0.47619048 0.14285714 0.23809524] [ 0.19047619 0.14285714 -0.0952381 ]] Matrix B is: [[ 6] [-4] [27]] Compute A-1B: [[ 5.] [ 3.] [-2.]]
使用函数可以获得相同的结果 –
x = np.dot(ainv,b)
NumPy – Matplotlib
Matplotlib是Python的绘图库。 它与NumPy一起使用,为MatLab提供了一个有效的开源替代方案。 它也可以用于像PyQt和wxPython这样的图形工具包。
Matplotlib模块首先由John D. Hunter编写。 自2012年以来,Michael Droettboom是主要开发人员。 目前,Matplotlib ver。 1.5.1是可用的稳定版本。 该软件包以二进制发行版以及www.matplotlib.org上的源代码格式提供。
通常,通过添加以下语句将包导入到Python脚本中 –
from matplotlib import pyplot as plt
这里pyplot()是matplotlib库中最重要的函数,用于绘制二维数据。 以下脚本绘制方程y = 2x + 5
import numpy as np from matplotlib import pyplot as plt x = np.arange(1,11) y = 2 * x + 5 plt.title("Matplotlib demo") plt.xlabel("x axis caption") plt.ylabel("y axis caption") plt.plot(x,y) plt.show()
ndarray对象x是由np.arange()函数创建的,作为x轴上的值。 y轴上的对应值存储在另一个ndarray对象y中。 这些值使用matplotlib软件包的pyplot子模块的plot()函数绘制。
图形表示由show()函数显示。
上面的代码应该产生以下输出 –
通过向plot()函数添加格式字符串,可以离散显示值而不是线性图。 可以使用格式化字符。
序号 | 字符 &描述 |
---|---|
1 | ‘-‘ 实线样式 |
2 | ‘–‘ 虚线样式 |
3 | ‘-.’ 点划线样式 |
4 | ‘:’ 虚线样式 |
5 | ‘.’ 点标记 |
6 | ‘,’ 像素标记 |
7 | ‘o’ 圆标记 |
8 | ‘v’ 三角向下标记 |
9 | ‘^’ 三角向上标记 |
10 | ‘&lt;’ 三角向左标记 |
11 | ‘&gt;’ 三角向右标记 |
12 | ‘1’ Tri_down标记 |
13 | ‘2’ Tri_up标记 |
14 | ‘3’ Tri_left标记 |
15 | ‘4’ Tri_right标记 |
16 | ‘s’ 方形标记 |
17 | ‘p’ 五角标记 |
18 | ‘*’ 星标 |
19 | ‘h’ Hexagon1标记 |
20 | ‘H’ Hexagon2标记 |
21 | ‘+’ 加号标记 |
22 | ‘x’ X标记 |
23 | ‘D’ 钻石标记 |
24 | ‘d’ 细钻石标记 |
25 | ‘|’ Vline标记 |
26 | ‘_’ Hline标记 |
以下颜色缩写也被定义。
字符 | 颜色 |
---|---|
‘b’ | 蓝 |
‘g’ | 绿色 |
‘r’ | 红色 |
‘c’ | 青色 |
‘m’ | 品红 |
‘y’ | 黄色 |
‘k’ | 黑 |
‘w’ | 白 |
要显示代表点的圆圈,而不是上面示例中的直线,请在plot()函数中使用“ob”作为格式字符串。
import numpy as np from matplotlib import pyplot as plt x = np.arange(1,11) y = 2 * x + 5 plt.title("Matplotlib demo") plt.xlabel("x axis caption") plt.ylabel("y axis caption") plt.plot(x,y,"ob") plt.show()
上面的代码应该产生以下输出 –
正弦波曲线
以下脚本使用matplotlib生成正弦波图。
import numpy as np import matplotlib.pyplot as plt # Compute the x and y coordinates for points on a sine curve x = np.arange(0, 3 * np.pi, 0.1) y = np.sin(x) plt.title("sine wave form") # Plot the points using matplotlib plt.plot(x, y) plt.show()
subplot()
subplot()函数允许你在同一个图中绘制不同的东西。 在下面的脚本中,绘制了正弦和余弦值。
import numpy as np import matplotlib.pyplot as plt # Compute the x and y coordinates for points on sine and cosine curves x = np.arange(0, 3 * np.pi, 0.1) y_sin = np.sin(x) y_cos = np.cos(x) # Set up a subplot grid that has height 2 and width 1, # and set the first such subplot as active. plt.subplot(2, 1, 1) # Make the first plot plt.plot(x, y_sin) plt.title('Sine') # Set the second subplot as active, and make the second plot. plt.subplot(2, 1, 2) plt.plot(x, y_cos) plt.title('Cosine') # Show the figure. plt.show()
上面的代码应该产生以下输出 –
bar()
pyplot子模块提供bar()函数来生成条形图。 以下示例生成两组x和y数组的条形图。
from matplotlib import pyplot as plt x = [5,8,10] y = [12,16,6] x2 = [6,9,11] y2 = [6,15,7] plt.bar(x, y, align = 'center') plt.bar(x2, y2, color = 'g', align = 'center') plt.title('Bar graph') plt.ylabel('Y axis') plt.xlabel('X axis') plt.show()
此代码应该产生以下输出 –
NumPy 使用Matplotlib的直方图
NumPy有一个numpy.histogram()函数,它是数据频率分布的图形表示。 相等的水平尺寸的长方形对应于类间隔称为bin和可变高度,对应于频率。
numpy.histogram()
numpy.histogram()函数将输入数组和数组作为两个参数。 箱阵列中的连续元素充当每个箱的边界。
import numpy as np a = np.array([22,87,5,43,56,73,55,54,11,20,51,5,79,31,27]) np.histogram(a,bins = [0,20,40,60,80,100]) hist,bins = np.histogram(a,bins = [0,20,40,60,80,100]) print hist print bins
它会产生以下输出 –
[3 4 5 2 1] [0 20 40 60 80 100]
plt()
Matplotlib可以将这个直方图的数字表示转换为图形。 pyplot子模块的plt()函数将包含数据和bin数组的数组作为参数并转换为直方图。
from matplotlib import pyplot as plt import numpy as np a = np.array([22,87,5,43,56,73,55,54,11,20,51,5,79,31,27]) plt.hist(a, bins = [0,20,40,60,80,100]) plt.title("histogram") plt.show()
它应该产生以下输出 –
NumPy 输入输出
ndarray对象可以保存到磁盘文件并从磁盘文件加载。 可用的IO功能是 –
- load()和save()函数处理/ numPy二进制文件(使用npy扩展名)
- loadtxt()和savetxt()函数处理普通的文本文件
NumPy为ndarray对象引入了一个简单的文件格式。 此.npy文件存储重建磁盘文件中的ndarray所需的数据,形状,dtype和其他信息,以便即使文件位于具有不同体系结构的另一台计算机上,也能正确检索该阵列。
numpy.save()
numpy.save()文件将输入数组存储在带有npy扩展名的磁盘文件中。
import numpy as np a = np.array([1,2,3,4,5]) np.save('outfile',a)
要从outfile.npy重建数组,请使用load()函数。
import numpy as np b = np.load('outfile.npy') print b
它会产生以下输出 –
array([1, 2, 3, 4, 5])
save()和load()函数接受一个额外的布尔参数allow_pickles。 在保存到磁盘文件或从磁盘文件读取数据之前,Python中的pickle用于序列化和反序列化对象。
savetxt()
以简单文本文件格式存储和检索数组数据是通过savetxt()和loadtxt()函数完成的。
import numpy as np a = np.array([1,2,3,4,5]) np.savetxt('out.txt',a) b = np.loadtxt('out.txt') print b
它会产生以下输出 –
[ 1. 2. 3. 4. 5.]
savetxt()和loadtxt()函数接受附加的可选参数,例如页眉,页脚和分隔符。