Numpy库介绍
[TOC]
Numpy库数据基本类型
| bool_ |
布尔型数据类型(True 或者 False) |
| int_ |
默认的整数类型(类似于 C 语言中的 long,int32 或 int64) |
| intc |
与 C 的 int 类型一样,一般是 int32 或 int 64 |
| intp |
用于索引的整数类型(类似于 C 的 ssize_t,一般情况下仍然是 int32 或 int64) |
| int8 |
字节(-128 to 127) |
| int16 |
整数(-32768 to 32767) |
| int32 |
整数(-2147483648 to 2147483647) |
| int64 |
整数(-9223372036854775808 to 9223372036854775807) |
| uint8 |
无符号整数(0 to 255) |
一、numpy数组的创建
arange格式
1
| numpy.arange(start, stop, step, dtype)
|
| 参数 |
描述 |
start |
起始值,默认为0 |
stop |
终止值(不包含) |
step |
步长,默认为1 |
dtype |
返回ndarray的数据类型,如果没有提供,则会使用输入数据的类型。 |
从列表创建
1.一维数组
1
| x = np.array([1,2,3,4,5],dtype="数据类型")
|
2.二维数组
1 2 3 4
| x = np.array([[1,2,3], [4,5,6], [7,8,9] ])
|
linspace格式创建
numpy.linspace 函数用于创建一个一维数组,数组是一个等差数列构成的,格式如下:
1
| np.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)
|
| 参数 |
描述 |
start |
序列的起始值 |
stop |
序列的终止值,如果endpoint为true,该值包含于数列中 |
num |
要生成的等步长的样本数量,默认为50 |
endpoint |
该值为 true 时,数列中包含stop值,反之不包含,默认是True。 |
retstep |
如果为 True 时,生成的数组中会显示间距,反之不显示。 |
dtype |
ndarray 的数据类型 |
均匀分配数组
该数组平均分配0~1,平均分配4份
logspace格式创建
numpy.logspace 函数用于创建一个于等比数列。格式如下:
1
| np.logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None)
|
| 参数 |
描述 |
start |
序列的起始值为:base ** start |
stop |
序列的终止值为:base ** stop。如果endpoint为true,该值包含于数列中 |
num |
要生成的等步长的样本数量,默认为50 |
endpoint |
该值为 true 时,数列中中包含stop值,反之不包含,默认是True。 |
base |
对数 log 的底数。 |
dtype |
ndarray 的数据类型 |
等比数列数组
zeros格式创建
创建指定大小的数组,数组元素以 0 来填充:
1
| numpy.zeros(shape, dtype = float, order = 'C')
|
参数说明:
| 参数 |
描述 |
| shape |
数组形状 |
| dtype |
数据类型,可选 |
| order |
‘C’ 用于 C 的行数组,或者 ‘F’ 用于 FORTRAN 的列数组 |
长度为5,值都为0的数组
ones格式创建
创建指定形状的数组,数组元素以 1 来填充:
1
| numpy.ones(shape, dtype = None, order = 'C')
|
参数说明:
| 参数 |
描述 |
| shape |
数组形状 |
| dtype |
数据类型,可选 |
| order |
‘C’ 用于 C 的行数组,或者 ‘F’ 用于 FORTRAN 的列数组 |
(2)2*4的浮点型数组
1
| np.ones((2,4),dtype=float)
|
full格式创建
填充一个指定格式的列表
用法:
1
| numpy.full(shape, fill_value, dtype=None, order='C', *, like=None)
|
| 参数 |
描述 |
| shape |
数组形状 |
| fill_value |
标量或类似数组 |
| dtype |
数据类型,可选 |
| order |
‘C’ 用于 C 的行数组,或者 ‘F’ 用于 FORTRAN 的列数组 |
| like |
允许创建非 NumPy 数组的引用对象 |
3*5的数组
二、从头创建数组
(4)3*3的单位矩阵
(8)随机数构成的数组
3*3的在0~1之间分布
(9)有均值、标准差的随机数构成的数组
1
| np.random.normal(0,1,(3,3))
|
(10)3*3的,在[0,10)之间随机整数构成的数组
1
| np.random.randint(0,10,size = (3,3))
|
(11)随机重排列
1 2
| x = np.array([10,20,30,40]) np.random.permutation(x)//不修改原列表
|
1
| np.random.shuffle(x)//修改原列表
|
(12)随机采样
1
| x = np.arange(10,25,dtype = float)
|
1
| np.random.choice(x,size=(4,3))
|
1
| np.random.choice(x,size=(4,3),p=x/np.sum(x))//
|
三、数组的性质
1
| x = np.random.randint(10,size=(3,4))
|
1.数组的形状shape
2.数组的维度ndim
3.数组的大小size
四、数组的索引
1.一维数组的索引
2.二维数组的索引
注:numpy数组的数据类型是固定的,向一个整数数组中加一个浮点数,会向下取整
五、数组的切片
1.一维数组—跟列表一样
2.多维数组—以二维数组为例