用于处理任意维度的数组
Numpy(Numerical Python)是一个开源的Python科学计算基础库,包含:
- 一个强大的N维数组对象 ndarray
- 广播功能函数
- 整合C/C++/Fortran代码的工具
- 线性代数、傅里叶变换、随机数生成等功能
- 同时Numpy是SciPy、 Pandas等数据处理或科学计算库的基础
numpy与Python原生list相比的优势
numpy数组在数值运算方面的效率优于Python提供的list容器。
- 内存结构 存储在内存中的一块联系存储区域,提高了数据的读取效率
- 并行运算
- 底层是用C语言编写的, 解放了GIL锁, 不受Python解释器的限制
import numpy as np
# 定义一个二维数组, dtype 定义类型
arr = np.array([[1,2,3],[3,4,4]],dtype=int)
print(arr)
数组的属性:
属性名字 |
属性解释 |
---|---|
ndarray.shape |
数组的形状,是一个元组,元素个数与维度相同 |
ndarray.ndim |
数组维数 |
ndarray.size |
数组中的元素数量 |
ndarray.itemsize |
一个数组元素的长度(字节) |
ndarray.dtype |
数组元素的类型 |
数组的类型:
名称 | 描述 | 简写 |
---|---|---|
np.bool | 用一个字节存储的布尔类型(True或False) | 'b' |
np.int8 | 一个字节大小,-128 至 127 | 'i' |
np.int16 | 整数,-32768 至 32767 | 'i2' |
np.int32 | 整数,-2 31 至 2 32 -1 | 'i4' |
np.int64 | 整数,-2 63 至 2 63 - 1 | 'i8' |
np.uint8 | 无符号整数,0 至 255 | 'u' |
np.uint16 | 无符号整数,0 至 65535 | 'u2' |
np.uint32 | 无符号整数,0 至 2 ** 32 - 1 | 'u4' |
np.uint64 | 无符号整数,0 至 2 ** 64 - 1 | 'u8' |
np.float16 | 半精度浮点数:16位,正负号1位,指数5位,精度10位 | 'f2' |
np.float32 | 单精度浮点数:32位,正负号1位,指数8位,精度23位 | 'f4' |
np.float64 | 双精度浮点数:64位,正负号1位,指数11位,精度52位 | 'f8' |
np.complex64 | 复数,分别用两个32位浮点数表示实部和虚部 | 'c8' |
np.complex128 | 复数,分别用两个64位浮点数表示实部和虚部 | 'c16' |
np.object_ | python对象 | 'O' |
np.string_ | 字符串 | 'S' |
np.unicode_ | unicode类型 | 'U' |
>>> a = np.array([[1, 2, 3],[4, 5, 6]], dtype=np.float32)
>>> a.dtype
dtype('float32')
注意:若不指定,整数默认int64,小数默认float64
生成数组的方式:
1 生成0和1的数组
- empty(shape[, dtype, order]) empty_like(a[, dtype, order, subok])
eye(N[, M, k, dtype, order]) - identity(n[, dtype])
- ones(shape[, dtype, order])
- ones_like(a[, dtype, order, subok])
- zeros(shape[, dtype, order]) zeros_like(a[, dtype, order, subok])
full(shape, fill_value[, dtype, order]) - full_like(a, fill_value[, dtype, order, subok])
>>> zero = np.zeros([3, 4])
array([[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.]])
2 从现有数组生成
-
array(object[, dtype, copy, order, subok, ndmin])
-
asarray(a[, dtype, order])
- asanyarray(a[, dtype, order]) ascontiguousarray(a[, dtype])
- asmatrix(data[, dtype])