【NumPy模块】
NumPy系统是Python的一种开源的数值计算扩展,一个用python实现的科学计算包。这种工具可用来存储和处理大型矩阵,比Python自身的嵌套列表(nested list structure)结构要高效的多(该结构也可以用来表示矩阵(matrix))。是python中的一款高性能,用于科学计算和数据分析的基础包。
NumPy的主要对象是一个强大的、同种元素的、N维数组对象Array。这是一个所有的元素都是一种类型、通过一个正整数元组索引的元素表格(通常是元素是数字)。NumPy的数组类被称作 ndarray 。通常被称作数组。
NumPy是高性能科学计算和数据分析的基础包。它是pandas等其他各种工具的基础。
NumPy的主要功能:ndarray,一个多维数组结构,高效且节省空间;无需循环对整组数据进行快速运算的数学函数
1
2
3
|
安装方法:pip install numpy
引用方式:
import
numpy as np
|
ndarray
ndarray(以下简称数组)是numpy的数组类对象,需要注意的是:它是同构的,也就是说其中的所有元素必须是相同的类型【用于科学计算都是数字类型:整数,小数】。其中每个数组都有一个shape(维度,几行几列)和dtype(数据类型)。
创建一个ndarray对象很简单,你可以使用 array
函数从常规的Python列表和元组创造数组,只要将一个list作为参数即可。所创建的数组类型由原序列中的元素类型推导而来。在NumPy中维度(dimensions)叫做轴(axis),轴的个数叫做秩(rank)。【0为行,1为列 用于做某一行或列操作】
例如,在3D空间一个点的坐标 [1, 2, 3] 是一个秩为1的数组,因为它只有一个轴。那个轴长度为3.又例如,在以下例子中,数组的秩为2(它有两个维度).第一个维度长度为2,第二个维度长度为3.
1
2
|
array([[
1.
,
0.
,
0.
],
[
0.
,
1.
,
2.
]])
|
ndarray对象常用属性
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
ndarray.ndim #数组轴的个数,在python的世界中,轴的个数被称作秩 ndarray.shape #数组的维度。这是一个指示数组在每个维度上大小的整数元组。例如一个n排m列的矩阵,它的shape属性将是(2,3),这个元组的长度显然是秩,即维度或者ndim属性 ndarray.size #数组元素的总个数,等于shape属性中元组元素的乘积。 ndarray.dtype #一个用来描述数组中元素类型的对象,可以通过创造或指定dtype使用标准Python类型。另外NumPy提供它自己的数据类型。 ndarray.itemsize #数组中每个元素的字节大小。例如,一个元素类型为float64的数组itemsiz属性值为8(=64/8),又如,一个元素类型为complex32的数组item属性为4(=32/8). ndarray.data #包含实际数组元素的缓冲区,通常我们不需要使用这个属性,因为我们总是通过索引来使用数组中的元素。
创建ndarray方法:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
array() 将列表转换为数组,可选择显式指定dtype
arange() range的numpy版,支持浮点数
linspace() 类似arange(),第三个参数为数组长度(数组元素个数)
zeros() 根据指定形状和dtype创建全0数组
ones() 根据指定形状和dtype创建全1数组
empty() 根据指定形状和dtype创建空数组(随机值)
reshape() 把一个arry类型的一维数组转成多维数组;参数为元组
eye() 根据指定边长和dtype创建单位矩阵
常用属性:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
数组的转置(对高维数组而言) dtype 数组元素的数据类型 dtype:bool_, int(8,16,32,64), uint(8,16,32,64), float(16,32,64) 数组的类型转换:astype() size 数组元素的个数 ndim 数组秩的个数 shape 数组的维度大小(以元组形式)
数组的创建
创建一个ndarray对象很简单,只要将一个list作为参数即可。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
import numpy as np #引入numpy库 #创建一维的narray对象 a = np.array([1,2,3,4,5]) #创建二维的narray对象 a1 = np.array([[1,2,3,4,5],[6,7,8,9,10]]) #创建多维对象以此类推 #执行结果 In [1]: import numpy as np ...: a = np.array([1,2,3,4,5]) ...: a1 = np.array([[1,2,3,4,5],[6,7,8,9,10]]) ...: In [2]: a,a1 Out[2]: (array([1, 2, 3, 4, 5]), array([[ 1, 2, 3, 4, 5], [ 6, 7, 8, 9, 10]]))
数组的常用属性
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
import numpy as np #引入numpy库 a = np.array([1,2,3,4,5]) a1 = np.array([[1,2,3,4,5],[6,7,8,9,10]]) a2 = np.array([[1.0,2.4,3.5],[8.1,6.3,7.6]]) print(type(a),type(a1),type(a2)) #查看数据类型 print(a.dtype,a1.dtype,a2.dtype) #查看数组的数据类型 print(a.ndim,a1.ndim,a2.ndim) #查看数组秩的个数 print(a1.size,a2.size) #数组内元素的总个数 print(a1.T) #数组转置 #执行结果 In [5]: import numpy as np #引入numpy库 ...: a = np.array([1,2,3,4,5]) ...: a1 = np.array([[1,2,3,4,5],[6,7,8,9,10]]) ...: a2 = np.array([[1.0,2.4,3.5],[8.1,6.3,7.6]]) ...: print(type(a),type(a1),type(a2)) #查看数据类型 ...: print(a.dtype,a1.dtype,a2.dtype) #查看数组的数据类型 ...: print(a.ndim,a1.ndim,a2.ndim) #查看数组秩的个数 ...: print(a1.size,a2.size) #数组内元素的总个数 ...: print(a1.T) #数组转置 ...: <class 'numpy.ndarray'> <class 'numpy.ndarray'> <class 'numpy.ndarray'> int32 int32 float64 1 2 2 10 6 [[ 1 6] [ 2 7] [ 3 8] [ 4 9] [ 5 10]] print(a.shape,a1.shape,a2.shape) #查看数组的维度 结果返回一个元组 n = a1.shape #获取数组a1的维度 print(n[0]) #获得行数 print(n[1]) #获得列数 #执行结果 In [6]: print(a.shape,a1.shape,a2.shape) #查看数组的维度 结果返回一个元组 ...: n = a1.shape #获取数组a1的维度(几行几列) ...: print(n[0]) #获得行数 ...: print(n[1]) #获得列数 ...: (5,) (2, 5) (2, 3) 2 5
数组类型可以在创建时可以指定
1
2
3
4
5
6
|
a
=
np.array([
1
,
2
,
3
,
4
,
5
],dtype
=
'float64'
)
#执行结果
In [
8
]: a
=
np.array([
1
,
2
,
3
,
4
,
5
],dtype
=
'float64'
)
In [
9
]: a
Out[
9
]: array([
1.
,
2.
,
3.
,
4.
,
5.
])
|
利用函数创建数组
1、为了创建一个数列,NumPy提供一个类似arange的函数返回一维数组而不是列表,同理也是顾头不顾尾:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
import
numpy as np
a
=
np.arange(
12
)
a1
=
np.arange(
0
,
12
,
3
)
#有步长的话,必须指定取值范围
#执行结果:
In [
24
]:
import
numpy as np
...: a
=
np.arange(
12
)
...: a1
=
np.arange(
0
,
12
,
3
)
#有步长的话,必须指定取值范围
...:
In [
26
]: a
Out[
26
]: array([
0
,
1
,
2
,
3
,
4
,
5
,
6
,
7
,
8
,
9
,
10
,
11
])
In [
27
]: a1
Out[
27
]: array([
0
,
3
,
6
,
9
])
|
2.1、也可以使用reshape()方法,把一个arry类型的一维数组转成多维数组。不管怎么得到的数据,只要是一维数组都可以使用reshape转换。【参数为元组】 但测试发现是普通数字或是列表也可以。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
In [
25
]: a
=
np.arange(
12
)
#建立二维
In [
28
]: a.reshape(
3
,
4
)
#3行4列
Out[
28
]:
array([[
0
,
1
,
2
,
3
],
[
4
,
5
,
6
,
7
],
[
8
,
9
,
10
,
11
]])
#建立三维
In [
32
]: a.reshape([
2
,
2
,
3
])
Out[
32
]:
array([[[
0
,
1
,
2
],
[
3
,
4
,
5
]],
[[
6
,
7
,
8
],
[
9
,
10
,
11
]]])
In [
33
]: a.reshape(
2
,
2
,
3
)
Out[
33
]:
array([[[
0
,
1
,
2
],
[
3
,
4
,
5
]],
[[
6
,
7
,
8
],
[
9
,
10
,
11
]]])
|
2.2、同时arange的步长可以为小数,也就是说我们可以得到浮点类型的数组,默认的dtype='float64';当需要生成浮点型数组时,需要指定范围
1
2
3
4
5
6
7
8
|
In [
34
]: b
=
np.arange(
0
,
5
,
0.5
)
In [
35
]: b
Out[
35
]: array([
0.
,
0.5
,
1.
,
1.5
,
2.
,
2.5
,
3.
,
3.5
,
4.
,
4.5
])
In [
39
]: b.reshape((
2
,
5
))
Out[
39
]:
array([[
0.
,
0.5
,
1.
,
1.5
,
2.
],
[
2.5
,
3.
,
3.5
,
4.
,
4.5
]])
|
2.3、当 arange 使用浮点数参数时,由于有限的浮点数精度,通常无法预测获得的元素个数。因此,最好使用函数 linspace 去接收我们想要数组元素总个数来代替用range指定的步长。
语法:linspace(a,b,size) 把某个范围分成多少份,size代表这个元组的大小或元组内的总个数。取值范围左右兼顾
1
2
3
4
5
6
7
8
9
10
11
|
In [
56
]: c
=
np.linspace(
1
,
5
,
5
)
In [
57
]: c
Out[
57
]: array([
1.
,
2.
,
3.
,
4.
,
5.
])
In [
58
]: c
=
np.linspace(
0
,
2
,
6
)
In [
59
]: c
Out[
59
]: array([
0.
,
0.4
,
0.8
,
1.2
,
1.6
,
2.
])
In [
60
]: c
=
np.linspace(
0
,
2
,
5
)
In [
61
]: c
Out[
61
]: array([
0.
,
0.5
,
1.
,
1.5
,
2.
])
|
通常,数组的元素开始都是未知的,但是它的大小已知。因此,NumPy提供了一些使用占位符创建数组的函数。这最小化了扩展数组的需要和高昂的运算代价。函数 zeros 创建一个全是0的数组,函数 ones 创建一个全1的数组,函数 empty 创建一个内容随机并且依赖于内存状态的数组。默认创建的数组类型(dtype)都是float64。
ones创建全1矩阵
zeros创建全0矩阵
eye创建单位矩阵 (对角线)
empty创建空矩阵(实际有值)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
In [
1
]:
import
numpy as np
In [
2
]: a_ones
=
np.ones((
3
,
4
))
# 创建3*4的全1矩阵
In [
3
]: a_ones
Out[
3
]:
array([[
1.
,
1.
,
1.
,
1.
],
[
1.
,
1.
,
1.
,
1.
],
[
1.
,
1.
,
1.
,
1.
]])
In [
4
]: a_zeros
=
np.zeros((
3
,
4
))
# 创建3*4的全0矩阵
In [
5
]: a_zeros
Out[
5
]:
array([[
0.
,
0.
,
0.
,
0.
],
[
0.
,
0.
,
0.
,
0.
],
[
0.
,
0.
,
0.
,
0.
]])
In [
7
]: a_eyes
=
np.eye((
3
))
# 创建3阶单位矩阵
In [
8
]: a_eyes
Out[
8
]:
array([[
1.
,
0.
,
0.
],
[
0.
,
1.
,
0.
],
[
0.
,
0.
,
1.
]])
In [
9
]: a_empty
=
np.empty((
3
,
4
))
# 创建3*4的空矩阵
In [
10
]: a_empty
Out[
10
]:
array([[
1.
,
1.
,
1.
,
1.
],
[
1.
,
1.
,
1.
,
1.
],
[
1.
,
1.
,
1.
,
1.
]])
|
注意:使用ones,zeros,eys创建数组的时候,是在内存中开辟一块空间,然后在里边传值;而empty仅仅只是在内存中开辟一块空间,根据python的回收机制,当某块内存某段时间内不使用的话,python就会把这块内存释放但内部数据还未清除,如果此时利用empty创建一个数组而又不传值,他就会把这块内存内存储的数据显示出来(显示的数据随机)。
数组的索引及切片
一维数组可以被索引、切片和迭代,就像列表一样;而多维数组是每行每列都有一个索引,当通过索引去取值的话,需要先取某一行数组然后再去取这一行某个值。
当切片取值的时候,一维数组和列表操作完全一致,而多维数组切片,中括号内需要传递两个切片索引,中间以逗号隔开,第一部分代表是对行切,第二部分代表是对列切!
与列表相同的是:当少于轴数的索引被提供时,缺失的索引被认为是整个切片;
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
#一维数组索引及切片操作 In [1]: import numpy as np In [2]: a = np.arange(12) In [3]: a Out[3]: array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) #索引 In [4]: a[0] Out[4]: 0 In [5]: a[-1] Out[5]: 11 #切片 In [6]: a[2:7] Out[6]: array([2, 3, 4, 5, 6]) In [7]: a[7:] Out[7]: array([ 7, 8, 9, 10, 11]) In [8]: a[::-1] Out[8]: array([11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]) #多维数组索引及切片操作 In [1]: import numpy as np In [2]: b = np.arange(12).reshape((3,4)) In [3]: b Out[3]: array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) #取多维数组的某行 In [4]: b[0] Out[4]: array([0, 1, 2, 3]) In [5]: b[2] Out[5]: array([ 8, 9, 10, 11]) #取数组内某一值(坐标为第3行和3列的数据) In [6]: b[2][2] Out[6]: 10 #多维数组切片 In [14]: b Out[14]: array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) In [15]: b[0:1] Out[15]: array([[0, 1, 2, 3]]) In [16]: b[0:2] Out[16]: array([[0, 1, 2, 3], [4, 5, 6, 7]]) #要求:取第1,2列前两行数据 #错误示范 In [17]: b[0:2][0:2] Out[17]: array([[0, 1, 2, 3], [4, 5, 6, 7]]) In [18]: b[0:2][2] --------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-18-9d1e92fd5c9c> in <module>() ----> 1 b[0:2][2] IndexError: index 2 is out of bounds for axis 0 with size 2 #正确示范 In [19]: b[0:2,2] Out[19]: array([2, 6]) In [20]: b[0:2,:2] Out[20]: array([[0, 1], [4, 5]])
注意:
1、数组也可以通过索引赋值;
2、多维数组通过索引取值的话,如果是写的是一个中括号,那取的是这个多维数组中的某一行;要取某一值的话,就需要在这行的数据上再通过索引取值。
当对多维数组进行切片的时候,如果按照索引的方式操作的话,第一次的切片操作得到的还是一个多维数组,再进行第二次切片的时候,操作的对象是切片得到的多维数组,所以说会出现超出索引范围或是结果不对的情况。要得到多维数组某行某列的值就需要只针对这个多维数组操作,把对行和列的切片放在一起,中间以逗号隔开。切片内,[,]逗号代表分割,左边是行,右边是列
切片中,关于视图与拷贝问题:
数组的切片与列表不同,数组切片时并不会自动复制,而是通过视图方法创造一个新的数组对象指向同一数据,当在切片数组上进行修改会影响原数组。(类似深拷贝)
相应的解决办法就是通过.copy()的方式,把要切片得到的数据拷贝一份,这样再对切片数组操作的时候就不会影响原数组。(类似浅拷贝)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
In [21]: b Out[21]: array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) #影响测试 In [22]: c = b[:,1:3] In [23]: c Out[23]: array([[ 1, 2], [ 5, 6], [ 9, 10]]) In [24]: c[0][0]=11 In [25]: c Out[25]: array([[11, 2], [ 5, 6], [ 9, 10]]) In [26]: b Out[26]: array([[ 0, 11, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) #非影响 copy()数据测试 In [29]: d = b[:,2:].copy() In [30]: d Out[30]: array([[ 2, 3], [ 6, 7], [10, 11]]) In [31]: d[0][1] =33 In [32]: d Out[32]: array([[ 2, 33], [ 6, 7], [10, 11]]) In [33]: b Out[33]: array([[ 0, 11, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]])
布尔索引
原理:多维数组特有的一种索引,会以索引内的条件对数组内的每个元素进行判断,返回一个布尔数组;然后将同样大小的布尔数组传进索引,会返回一个由所有True对应位置的元素的数组。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
#生成一个多维数组 In [34]: a = np.arange(12).reshape((3,4)) In [35]: a Out[35]: array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) #得到布尔数组 In [36]: a>5 Out[36]: array([[False, False, False, False], [False, False, True, True], [ True, True, True, True]], dtype=bool) #通过布尔数组获取数组内所有大于5的数 In [37]: a[a>5] Out[37]: array([ 6, 7, 8, 9, 10, 11])
布尔索引进阶 (布尔数组和逻辑运算【与 &,或 |,非 ~】)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
In [38]: a Out[38]: array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) #选出数组中所有大于5的偶数。 In [39]: a[(a>5) & (a%2==0)] Out[39]: array([ 6, 8, 10]) #选出数组中所有大于5的数和偶数。 In [40]: a[(a>5) | (a%2==0)] Out[40]: array([ 0, 2, 4, 6, 7, 8, 9, 10, 11]) #选出数组中所有小于5的偶数。 In [43]: a[~(a>5) & (a%2==0)] Out[43]: array([0, 2, 4]) #选出数组中所有大于5的奇数。 In [44]: a[(a>5) & (~(a%2==0))] Out[44]: array([ 7, 9, 11])
花式索引:
按照对应位置组成一个列表,逗号隔开;然后这个数组通过这个索引列表取出元素,组成新的数组。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
#对于一个数组,选出其第1,3,4,6,7个元素,组成新的数组。 In [56]: b = np.arange(5,20) In [57]: b Out[57]: array([ 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]) In [58]: b[[1,2,3,4,6,7]] Out[58]: array([ 6, 7, 8, 9, 11, 12]) #对一个二维数组,选出其第一列和第三列,组成新的二维数组。 #创建一个二维数组 In [61]: a = np.arange(10).reshape(2,5) In [62]: a Out[62]: array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]) #切片截取第一和第三列组成新的数组 In [64]: a[:,[0,2]] Out[64]: array([[0, 2], [5, 7]]) 数组运算
数组运算
3.1、常用数组运算符
大小相等的数组之间做任何算术运算都会将运算应用到元素级别。
1
2
3
4
5
6
7
|
运算符 说明
+
矩阵对应元素相加
-
矩阵对应元素相减
*
矩阵对应元素相乘
/
矩阵对应元素相除,如果都是整数则取商
%
矩阵对应元素相除后取余数
*
*
矩阵每个元素都取n次方,如
*
*
2
:每个元素都取平方
|
注意:
计算越界问题:当对整数进行乘法或是阶乘运算时,可能最后得到的结果超出了数组定义的数据类型范围,出现数据不正确的情况;
解决办法:把元组内的数据转成浮点型,然后再做计算,结果会以科学计算法的形式展示。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
In [12]: arr = np.arange(9).reshape((3,3)) In [13]: arr Out[13]: array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) In [14]: arr+1 Out[14]: array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) In [15]: arr*2 Out[15]: array([[ 0, 2, 4], [ 6, 8, 10], [12, 14, 16]]) In [16]: arr**2 Out[16]: array([[ 0, 1, 4], [ 9, 16, 25], [36, 49, 64]], dtype=int32) In [17]: arr1 = np.arange(9,18).reshape((3,3)) In [18]: arr1 Out[18]: array([[ 9, 10, 11], [12, 13, 14], [15, 16, 17]]) In [19]: arr/arr1 Out[19]: array([[ 0. , 0.1 , 0.18181818], [ 0.25 , 0.30769231, 0.35714286], [ 0.4 , 0.4375 , 0.47058824]]) In [20]: arr+arr1 Out[20]: array([[ 9, 11, 13], [15, 17, 19], [21, 23, 25]])
通用函数:
通用函数:不用循环就能处理数组中所有的元素完成运算的函数
明确两点:
inf 无限大 例:5/0
nan 不是数【not a number】 例:0/0
常见通用函数:
一元函数:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
abs
(绝对值),
sqrt,开跟号
exp,
log,
ceil, 向上取整
floor, 向下取整
rint
/
round
,四舍五入变整数:
trunc, 向
0
取整,接近
0
的整数
modf, 把一个浮点类型数组转换成两个数组:一个是小数数组,一个是整数数组
isnan(判断数据类型是否是nan【
not
a number】),
isinf(判断数据类型那个是否是inf),
cos,
sin,
tan,
|
示例代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
In [3]: a = np.arange(0,3,0.2) In [4]: a Out[4]: array([ 0. , 0.2, 0.4, 0.6, 0.8, 1. , 1.2, 1.4, 1.6, 1.8, 2. , 2.2, 2.4, 2.6, 2.8]) In [7]: np.ceil(3.4) Out[7]: 4.0 In [8]: np.floor(3.4) Out[8]: 3.0 In [9]: np.ceil(-3.4) Out[9]: -3.0 In [10]: np.floor(-3.4) Out[10]: -4.0 In [11]: np.trunc(-3.4) Out[11]: -3.0 In [12]: np.trunc(3.4) Out[12]: 3.0 In [13]: np.round(a) Out[13]: array([ 0., 0., 0., 1., 1., 1., 1., 1., 2., 2., 2., 2., 2., 3., 3.]) In [14]: np.modf(a) Out[14]: (array([ 0. , 0.2, 0.4, 0.6, 0.8, 0. , 0.2, 0.4, 0.6, 0.8, 0. , 0.2, 0.4, 0.6, 0.8]), array([ 0., 0., 0., 0., 0., 1., 1., 1., 1., 1., 2., 2., 2., 2., 2.])) In [15]: b = np.array([1,2,3,4,5]) In [16]: c = np.array([1,2,3,4,0]) In [17]: d = b/c C:\Program Files\Python36\Scripts\ipython:1: RuntimeWarning: divide by zero encountered in true_divide In [19]: d Out[19]: array([ 1., 1., 1., 1., inf]) #判断是不是inf返回布尔值 In [20]: np.isinf(d) Out[20]: array([False, False, False, False, True], dtype=bool) #使用布尔索引,取不是inf的元素 In [21]: d[~np.isinf(d)] Out[21]: array([ 1., 1., 1., 1.]) In [26]: a = np.array([1,2,3,4,0]) In [27]: b = np.array([1,2,3,4,0]) In [28]: c = a/b C:\Program Files\Python36\Scripts\ipython:1: RuntimeWarning: invalid value encountered in true_divide In [29]: c Out[29]: array([ 1., 1., 1., 1., nan]) #判断是不是nan返回布尔值 In [30]: np.isnan(c) Out[30]: array([False, False, False, False, True], dtype=bool) #使用布尔索引,取不是nan的元素 In [32]: c[~np.isnan(c)] Out[32]: array([ 1., 1., 1., 1.])
二元函数:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
add, 加
substract,减
multiply, 乘
divide,除
power, 平方
mod,
maximum, 两数组对应位置上的元素相比较,取最大的数,组成一个新数组
mininum, 两数组对应位置上的元素相比较,取最小的数,组成一个新数组
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
In [1]: import numpy as np #定义两个数组 In [2]: a = np.array([1,3,2,4,5]) In [3]: b = np.array([3,2,1,5,4]) In [6]: a Out[6]: array([1, 3, 2, 4, 5]) In [7]: b Out[7]: array([3, 2, 1, 5, 4]) #两比较取最大 In [8]: np.maximum(a,b) Out[8]: array([3, 3, 2, 5, 5]) #两比较取最小 In [9]: np.minimum(a,b) Out[9]: array([1, 2, 1, 4, 4])
NumPy 中数学和统计方法
1
2
3
4
5
6
7
8
9
10
|
常用函数:
sum
求和
umsum 求累计和
-
-
当前位置的元素与前面元素相加的和
mean 求平均数
std 求标准差
var 求方差
-
-
每个数到平均数的差的平方和再取平均值
min
求最小值
-
一个数组内最小值
max
求最大值
-
一个数组内最大值
argmin 求最小值索引
-
-
一个数组内最小值下标
argmax 求最大值索引
-
-
一个数组内最大值下标
|
示例代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
|
最大最小值
获得矩阵中元素最大最小值的函数分别是
max
和
min
,可以获得整个矩阵、行或列的最大最小值。
import
numpy as np
a
=
np.array([[
1
,
2
,
3
],[
4
,
5
,
6
]])
print
(a.
max
())
#获取整个矩阵的最大值 结果: 6
print
(a.
min
())
#结果:1
# 可以指定关键字参数axis来获得行最大(小)值或列最大(小)值
# axis=0 行方向最大(小)值,即获得每列的最大(小)值
# axis=1 列方向最大(小)值,即获得每行的最大(小)值
print
(a.
max
(axis
=
0
))
# 结果为 [4 5 6]
print
(a.
max
(axis
=
1
))
# 结果为 [3 6]
# 要想获得最大最小值元素所在的位置,可以通过argmax函数来获得
print
(a.argmax(axis
=
1
))
# 结果为 [2 2]
平均值
获得矩阵中元素的平均值可以通过函数mean()。同样地,可以获得整个矩阵、行或列的平均值。
import
numpy as np
a
=
np.array([[
1
,
2
,
3
],[
4
,
5
,
6
]])
print
(a.mean())
#结果为: 3.5
# 同样地,可以通过关键字axis参数指定沿哪个方向获取平均值
print
(a.mean(axis
=
0
))
# 结果 [ 2.5 3.5 4.5]
print
(a.mean(axis
=
1
))
# 结果 [ 2. 5.]
方差
方差的函数为var(),方差函数var()相当于函数mean(
abs
(x
-
x.mean())
*
*
2
),其中x为矩阵。
import
numpy as np
a
=
np.array([[
1
,
2
,
3
],[
4
,
5
,
6
]])
print
(a.var())
# 结果 2.91666666667
print
(a.var(axis
=
0
))
# 结果 [ 2.25 2.25 2.25]
print
(a.var(axis
=
1
))
# 结果 [ 0.66666667 0.66666667]
标准差
标准差的函数为std()。 std()相当于sqrt(mean(
abs
(x
-
x.mean())
*
*
2
)),或相当于sqrt(x.var())。
import
numpy as np
a
=
np.array([[
1
,
2
,
3
],[
4
,
5
,
6
]])
print
(a.std())
# 结果 1.70782512766
print
(a.std(axis
=
0
))
# 结果 [ 1.5 1.5 1.5]
print
(a.std(axis
=
1
))
# 结果 [ 0.81649658 0.81649658]
中值
中值指的是将序列按大小顺序排列后,排在中间的那个值,如果有偶数个数,则是排在中间两个数的平均值。
例如序列[
5
,
2
,
6
,
4
,
2
],按大小顺序排成 [
2
,
2
,
4
,
5
,
6
],排在中间的数是
4
,所以这个序列的中值是
4
。
又如序列[
5
,
2
,
6
,
4
,
3
,
2
],按大小顺序排成 [
2
,
2
,
3
,
4
,
5
,
6
],因为有偶数个数,排在中间两个数是
3
、
4
,所以这个序列中值是
3.5
。
中值的函数是median(),调用方法为numpy.median(x,[axis]),axis可指定轴方向,默认axis
=
None
,对所有数去中值。
import
numpy as np
x
=
np.array([[
1
,
2
,
3
],[
4
,
5
,
6
]])
print
(np.median(x))
# 对所有数取中值
# 结果 3.5
print
(np.median(x,axis
=
0
))
# 沿第一维方向取中值
# 结果 [ 2.5 3.5 4.5]
print
(np.median(x,axis
=
1
))
# 沿第二维方向取中值
# 结果[ 2. 5.]
求和
矩阵求和的函数是
sum
(),可以对行,列,或整个矩阵求和
import
numpy as np
a
=
np.array([[
1
,
2
,
3
],[
4
,
5
,
6
]])
print
(a.
sum
())
# 对整个矩阵求和
# 结果 21
print
(a.
sum
(axis
=
0
))
# 对行方向求和
# 结果 [5 7 9]
print
(a.
sum
(axis
=
1
))
# 对列方向求和
# 结果 [ 6 15]
累积和
某位置累积和指的是该位置之前(包括该位置)所有元素的和。
例如序列[
1
,
2
,
3
,
4
,
5
],其累计和为[
1
,
3
,
6
,
10
,
15
],即第一个元素为
1
,第二个元素为
1
+
2
=
3
,……,第五个元素为
1
+
2
+
3
+
4
+
5
=
15
。
矩阵求累积和的函数是cumsum(),可以对行,列,或整个矩阵求累积和。
import
numpy as np
a
=
np.array([[
1
,
2
,
3
],[
4
,
5
,
6
]])
print
(a.cumsum())
# 对整个矩阵求累积和
# 结果 [ 1 3 6 10 15 21]
print
(a.cumsum(axis
=
0
))
# 对行方向求累积和
# 结果
[[
1
2
3
]
[
5
7
9
]]
print
(a.cumsum(axis
=
1
))
# 对列方向求累积和
# 结果
[[
1
3
6
]
[
4
9
15
]]
|
random 生成随机数
实质上就是重写了Python的random模块
1
2
3
4
5
6
7
|
常用函数
rand 给定形状产生随机数组(
0
到
1
之间的数)
randint 给定形状产生随机整数 (数组)
choice 给定形状产生随机选择
shuffle 与random.shuffle相同 (洗牌)
uniform 给定形状产生随机小数(数组)
|
示例代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
In [66]: import numpy as np #rand测试 In [67]: np.random.rand() Out[67]: 0.31627484569427544 In [68]: np.random.rand() Out[68]: 0.27011813480098346 #randint测试 In [69]: np.random.randint(1,3) Out[69]: 2 In [70]: np.random.randint(1,3) Out[70]: 2 In [71]: np.random.randint(1,3) Out[71]: 2 In [72]: np.random.randint(1,3) Out[72]: 1 In [2]: np.random.randint(1,3,10) Out[2]: array([1, 1, 1, 1, 1, 1, 2, 1, 2, 1]) In [73]: l = [1,2,3,4,5] #choice测试 In [74]: np.random.choice(l) Out[74]: 1 In [75]: np.random.choice(l) Out[75]: 5 In [76]: np.random.choice(l) Out[76]: 2 In [85]: np.random.choice(l,4) Out[85]: array([2, 1, 4, 3]) In [86]: np.random.choice(l,3) Out[86]: array([3, 4, 1]) #洗牌测试 In [77]: np.random.shuffle(l) In [78]: l Out[78]: [5, 4, 3, 2, 1] In [79]: np.random.shuffle(l) In [80]: l Out[80]: [5, 4, 1, 2, 3] #范围内小数测试 In [81]: np.random.uniform(1,2) Out[81]: 1.3473541275258798 In [82]: np.random.uniform(1,2) Out[82]: 1.2320202461818281 In [83]: np.random.uniform(1,2) Out[83]: 1.6726333608929713 In [84]: np.random.uniform(l) Out[84]: array([ 1.49064608, 1.46376829, 1. , 1.49454 , 2.51421719])
补充:
关于数组的显示问题:当数组内的数据不多的时候会全部显示,当数据大到足以会显示首尾,中间的以...略过,数据是真实存在的只是隐藏了!一维数组被打印成行,二维数组成矩阵,三维数组成矩阵列表。