-
Numpy(Numeric Python)是应用Python进行科学计算时的基础模块。它是一个提供多维数组对象的Python库,除此之外,还包含了多种衍生的对象(比如掩码式数组(masked arrays)或矩阵)以及一系列的为快速计算数组而生的例程,包括数学运算,逻辑运算,形状操作,排序,选择,I/O,离散傅里叶变换,基本线性代数,基本统计运算,随机模拟等等。
-
Numpy库中最核心的部分是ndarray 对象。它封装了同构数据类型的n维数组,它的功能将通过演示代码的形式呈现。 NumPy数组和标准Python序列之间有几个重要区别:
(1)Numpy数组在创建时就会有一个固定的尺寸,这一点和Python中的list数据类型(可以动态生长)是不同的。当Numpy数组的尺寸发生改变时其实会删除之前的而创建一个新的数组。
(2)在一个Numpy数组中的所有元素数组类型要一致,并在内存中占有相同的大小。这里有一点例外:可以在Python的数组中包含Numpy的对象,这样的话就可以实现不同类型的元素。
(3)在数据量巨大时,使用Numpy进行高级数据运算和其他类型的操作是更为方便的。 通常情况下,这样的操作比使用Python的内置序列更有效,执行代码更少。
(4)越来越多的用于数学和科学计算Python库使用了Numpy,虽然这些第三方库也留了Python内置序列的输入接口,但是实际上在处理这些输入前还是要转成Numpy数组,平切这些库的输出一般是Numpy数组。换句话说,为了更好的使用当今大多数(甚至是绝大多数)用于数学/科学的Python库,仅仅知道Python本身是远远不够的。
在科学计算中序列的大小和速度是尤其重要的点。举个简单的例子:如果要将一个一维的序列a中的每一个数与另一个序列b(长度与a相同)。数据存放在python的list结构中,通过遍历列表可以得到:
NumPy - Ndarray 对象
NumPy 中定义的最重要的对象是称为 ndarray
的 N 维数组类型。 它描述相同类型的元素集合。 可以使用基于零的索引访问集合中的项目。
ndarray
中的每个元素在内存中使用相同大小的块。 ndarray
中的每个元素是数据类型对象的对象(称为 dtype
)。
从ndarray
对象提取的任何元素(通过切片)由一个数组标量类型的 Python 对象表示。 下图显示了ndarray
,数据类型对象(dtype
)和数组标量类型之间的关系。
Ndarray
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. | ndimin 指定返回数组的最小维数。 |
看看下面的例子来更好地理解。
示例 1
import numpy as np
a = np.array([1,2,3])
print a
输出如下:
[1, 2, 3]
示例 2
# 多于一个维度
import numpy as np
a = np.array([[1, 2], [3, 4]])
print a
输出如下:
[[1, 2]
[3, 4]]
示例 3
# 最小维度
import numpy as np
a = np.array([1, 2, 3,4,5], ndmin = 2)
print a
输出如下:
[[1, 2, 3, 4, 5]]
示例 4
# dtype 参数
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_ 存储为一个字节的布尔值(真或假) |
2. | int_ 默认整数,相当于 C 的long ,通常为int32 或int64 |
3. | intc 相当于 C 的int ,通常为int32 或int64 |
4. | intp 用于索引的整数,相当于 C 的size_t ,通常为int32 或int64 |
5. | int8 字节(-128 ~ 127) |
6. | int16 16 位整数(-32768 ~ 32767) |
7. | int32 32 位整数(-2147483648 ~ 2147483647) |
8. | int64 64 位整数(-9223372036854775808 ~ 9223372036854775807) |
9. | uint8 8 位无符号整数(0 ~ 255) |
10. | uint16 16 位无符号整数(0 ~ 65535) |
11. | uint32 32 位无符号整数(0 ~ 4294967295) |
12. | uint64 64 位无符号整数(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
(数据类型)对象的实例,每个对象具有唯一的特征。 这些类型可以是np.bool_
,np.float32
等。
数据类型对象 (dtype
)
数据类型对象描述了对应于数组的固定内存块的解释,取决于以下方面:
-
数据类型(整数、浮点或者 Python 对象)
-
数据大小
-
字节序(小端或大端)
-
在结构化类型的情况下,字段的名称,每个字段的数据类型,和每个字段占用的内存块部分。
-
如果数据类型是子序列,它的形状和数据类型。
字节顺序取决于数据类型的前缀<
或>
。 <
意味着编码是小端(最小有效字节存储在最小地址中)。 >
意味着编码是大端(最大有效字节存储在最小地址中)。
dtype
可由一下语法构造:
numpy.dtype(object, align, copy)
参数为:
-
Object
:被转换为数据类型的对象。 -
Align
:如果为true
,则向字段添加间隔,使其类似 C 的结构体。 -
Copy
? 生成dtype
对象的新副本,如果为flase
,结果是内建数据类型对象的引用。
示例 1
# 使用数组标量类型
import numpy as np
dt = np.dtype(np.int32)
print dt
输出如下:
int32
示例 2
#int8,int16,int32,int64 可替换为等价的字符串 'i1','i2','i4',以及其他。
import numpy as np
dt = np.dtype('i4')
print dt
输出如下:
int32
示例 3
# 使用端记号
import numpy as np
dt = np.dtype('>i4')
print dt
输出如下:
>i4
下面的例子展示了结构化数据类型的使用。 这里声明了字段名称和相应的标量数据类型。
示例 4
# 首先创建结构化数据类型。
import numpy as np
dt = np.dtype([('age',np.int8)])
print dt
输出如下:
[('age', 'i1')]
示例 5
# 现在将其应用于 ndarray 对象
import numpy as np
dt = np.dtype([('age',np.int8)])
a = np.array([(10,),(20,),(30,)], dtype = dt)
print a
输出如下:
[(10,) (20,) (30,)]
示例 6
# 文件名称可用于访问 age 列的内容
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'
:布尔值 -
'i'
:符号整数 -
'u'
:无符号整数 -
'f'
:浮点 -
'c'
:复数浮点 -
'm'
:时间间隔 -
'M'
:日期时间 -
'O'
:Python 对象 -
'S', 'a'
:字节串 -
'U'
:Unicode -
'V'
:原始数据(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
# 这会调整数组大小
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 也提供了reshape
函数来调整数组大小。
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
# 等间隔数字的数组
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
# 一维数组
import numpy as np
a = np.arange(24) a.ndim
# 现在调整其大小
b = a.reshape(2,4,3)
print b
# b 现在拥有三个维度
输出如下:
[[[ 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 为 int8(一个字节)
import numpy as np
x = np.array([1,2,3,4,5], dtype = np.int8)
print x.itemsize
输出如下:
1
示例 2
# 数组的 dtype 现在为 float32(四个字节)
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) 数据区域可写入。 将它设置为flase 会锁定数据,使其只读 |
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' 为按行的 C 风格数组,'F' 为按列的 Fortran 风格数组 |
示例
下面的代码展示空数组的例子:
import numpy as np
x = np.empty([3,2], dtype = int)
print x
输出如下:
[[22649312 1701344351]
[1818321759 1885959276]
[16779776 156368896]]
注意:数组元素为随机值,因为它们未初始化。
numpy.zeros
返回特定大小,以 0 填充的新数组。
numpy.zeros(shape, dtype = float, order = 'C')
构造器接受下列参数:
序号 | 参数及描述 |
---|---|
1. | Shape 空数组的形状,整数或整数元组 |
2. | Dtype 所需的输出数组类型,可选 |
3. | Order 'C' 为按行的 C 风格数组,'F' 为按列的 Fortran 风格数组 |
示例 1
# 含有 5 个 0 的数组,默认类型为 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
# 自定义类型
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' 为按行的 C 风格数组,'F' 为按列的 Fortran 风格数组 |
示例 1
# 含有 5 个 1 的数组,默认类型为 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' 为按行的 C 风格数组,'F' 为按列的 Fortran 风格数组 |
下面的例子展示了如何使用asarray
函数:
示例 1
# 将列表转换为 ndarray
import numpy as np
x = [1,2,3]
a = np.asarray(x)
print a
输出如下:
[1 2 3]
示例 2
# 设置了 dtype
import numpy as np
x = [1,2,3]
a = np.asarray(x, dtype = float)
print a
输出如下:
[ 1. 2. 3.]
示例 3
# 来自元组的 ndarray
import numpy as np
x = (1,2,3)
a = np.asarray(x)
print a
输出如下:
[1 2 3]
示例 4
# 来自元组列表的 ndarray
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 返回数组的数据类型,默认为float |
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
# 使用 range 函数创建列表对象
import numpy as np
list = range(5)
print list
输出如下:
[0, 1, 2, 3, 4]
示例 2
# 从列表中获得迭代器
import numpy as np
list = range(5)
it = iter(list)
# 使用迭代器创建 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
x = np.arange(5, dtype = float)
print x
输出如下:
[0. 1. 2. 3. 4.]
示例 3
# 设置了起始值和终止值参数
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 序列的终止值,如果endpoint 为true ,该值包含于序列中 |
3. | num 要生成的等间隔样例数量,默认为50 |
4. | endpoint 序列中是否包含stop 值,默认为ture |
5. | retstep 如果为true ,返回样例,以及连续数字之间的步长 |
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 设为 false
import numpy as np
x = np.linspace(10,20, 5, endpoint = False)
print x
输出如下:
[10. 12. 14. 16. 18.]
示例 3
# 输出 retstep 值
import numpy as np
x = np.linspace(1,2,5, retstep = True)
print x
# 这里的 retstep 为 0.25
输出如下:
(array([ 1. , 1.25, 1.5 , 1.75, 2. ]), 0.25)
numpy.logspace
此函数返回一个ndarray
对象,其中包含在对数刻度上均匀分布的数字。 刻度的开始和结束端点是某个底数的幂,通常为 10。
numpy.logscale(start, stop, num, endpoint, base, dtype)
logspace
函数的输出由以下参数决定:
序号 | 参数及描述 |
---|---|
1. | start 起始值是base ** start |
2. | stop 终止值是base ** stop |
3. | num 范围内的数值数量,默认为50 |
4. | endpoint 如果为true ,终止值包含在输出数组当中 |
5. | base 对数空间的底数,默认为10 |
6. | dtype 输出数组的数据类型,如果没有提供,则取决于其它参数 |
下面的例子展示了logsp