NumPy 最重要的一个特点是其 N 维数组对象 ndarray,它是一系列同类型数据的集合,以 0 下标为开始进行集合中元素的索引。
ndarray 对象是用于存放同类型元素的多维数组。
ndarray 中的每个元素在内存中都有相同存储大小的区域。
ndarray 内部由以下内容组成:
一个指向数据(内存或内存映射文件中的一块数据)的指针。
数据类型或 dtype,描述在数组中的固定大小值的格子。
一个表示数组形状(shape)的元组,表示各维度大小的元组。
一个跨度元组(stride),其中的整数指的是为了前进到当前维度下一个元素需要"跨过"的字节数。
numpy.array(object, dtype = None, copy = True, order = None, subok = False, ndmin = 0)
object | 数组或嵌套的数列 |
dtype | 数组元素的数据类型,可选 |
copy | 对象是否需要复制,可选 |
order | 创建数组的样式,C为行方向,F为列方向,A为任意方向(默认) |
subok | 默认返回一个与基类类型一致的数组 |
ndmin | 指定生成数组的最小维度 |
#最小维度 import numpy as np a = np.array([1, 2, 3,4,5], ndmin = 2) print (a) #结果 [[1 2 3 4 5]]
#dtype参数复数 import numpy as np a = np.array([1.01, 2, 3,4,5], dtype=complex) print (a) #结果 [ 1.+0.j, 2.+0.j, 3.+0.j]
NumPy数据类型
numpy支持的数据类型比python内置的数据类型要多,基本上可以和C语言的数据类型对应上,其中部分类型对应python内置类型
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) |
uint16 | 无符号整数(0 to 65535) |
uint32 | 无符号整数(0 to 4294967295) |
uint64 | 无符号整数(0 to 18446744073709551615) |
float_ | float64 类型的简写 |
float16 | 半精度浮点数,包括:1 个符号位,5 个指数位,10 个尾数位 |
float32 | 单精度浮点数,包括:1 个符号位,8 个指数位,23 个尾数位 |
float64 | 双精度浮点数,包括:1 个符号位,11 个指数位,52 个尾数位 |
complex_ | complex128 类型的简写,即 128 位复数 |
complex64 | 复数,表示双 32 位浮点数(实数部分和虚数部分) |
complex128 | 复数,表示双 64 位浮点数(实数部分和虚数部分) |
numpy的数值类型实际上是dtype对象的实例,并对应唯一的字符,包括np.bool_, np.init32,np.float32,等等
数据类型对象 (dtype)
数据类型对象是用来描述与数组对应的内存区域如何使用,这依赖如下几个方面:
- 数据的类型(整数,浮点数或者 Python 对象)
- 数据的大小(例如, 整数使用多少个字节存储)
- 数据的字节顺序(小端法或大端法)
- 在结构化类型的情况下,字段的名称、每个字段的数据类型和每个字段所取的内存块的部分
- 如果数据类型是子数组,它的形状和数据类型
numpy.dtype(object, align, copy)
- object - 要转换为的数据类型对象
- align - 如果为 true,填充字段使其类似 C 的结构体。
- copy - 复制 dtype 对象 ,如果为 false,则是对内置数据类型对象的引用
import numpy as np #使用标量类型 dt = np.dtype(np.int32) #结果 int32
import numpy as np # int8, int16, int32, int64 四种数据类型可以使用字符串 'i1', 'i2','i4','i8' 代替 dt = np.dtype('i4') print(dt) #结果 int32
import numpy as np # 字节顺序标注 dt = np.dtype('<i4') print(dt) #结果 int32
# 首先创建结构化数据类型 import numpy as np dt = np.dtype([('age',np.int8)]) print(dt) #结果 [('age','i1')]
# 将数据类型应用于 ndarray 对象 import numpy as np dt = np.dtype([('age',np.int8)]) a = np.array([(10,),(20,),(30,)], dtype = dt) print(a) #结果 [(10,) (20,) (30,)]
# 类型字段名可以用于存取实际的 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]
import numpy as np student = np.dtype([('name','S20'), ('age', 'i1'), ('marks', 'f4')]) print(student) #结果 [('name', 'S20'), ('age', 'i1'), ('marks', '<f4')]
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 | 无符号整型 integer |
f | 浮点型 |
c | 复数浮点型 |
m | timedelta(时间间隔) |
M | datetime(日期时间) |
O | (Python) 对象 |
S, a | (byte-)字符串 |
U | Unicode |
V | 原始数据 (void) |
numpy数组属性
numpy数组的维数成为秩(rank),一维数组的秩为1,二维数组的秩成为2,以此类推。
在numpy中,每一个线性数组为一个轴(axis),也就是维度(dimensions).比如说。二维数组相当于两个一维数组,其中第一个一维数据中每个元素又是一维数组。所以一维数组就是numpy中的轴(axis),第一个轴相当于是底层数组,第二个轴是底层数组里的数组。而轴的数量——秩,就是数组的维数。
很多时候可以声明axis. axis=0,表示沿着第0轴进行操作,即对每一列进行操作;zxis=1,表示个轴进行操作沿着第一个轴进行操作,即对每一行进行操作。
numpy的数组中比较重要的ndarray对象属性:
ndarray.ndim | 秩,即轴的数量或维度的数量 |
ndarray.shape | 数组的维度,对于矩阵,n 行 m 列 |
ndarray.size | 数组元素的总个数,相当于 .shape 中 n*m 的值 |
ndarray.dtype | ndarray 对象的元素类型 |
ndarray.itemsize | ndarray 对象中每个元素的大小,以字节为单位 |
ndarray.flags | ndarray 对象的内存信息 |
ndarray.real | ndarray元素的实部 |
ndarray.imag | ndarray 元素的虚部 |
ndarray.data | 包含实际数组元素的缓冲区,由于一般通过数组的索引获取元素,所以通常不需要使用这个属性。 |
import numpy as np a = np.arange(24) b = a.reshape(2,3,4) # b 现在拥有三个维度 print(b) print (b.ndim) #结果 [[[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] [[12 13 14 15] [16 17 18 19] [20 21 22 23]]] 3
ndarray.shape(也可以用于调整数组大小)
ndarray.shape表示数组的维度,返回一个元组,这个元组的长度就是维度的数目,即 ndim 属性(秩)。比如,一个二维数组,其维度表示"行数"和"列数"。
import numpy as np a= np.array([[1,2,3],[4,5,6]]) print(a.shape) #结果 (2,3)
#调试大小 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]]
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.itemsize
ndarray.itemsize以字节的形式返回数组中每一个元素的大小
例如,一个元素类型为float64的数组itemsiz属性值为8(float64占用64个bits,每个字节长度8,所以64/8,占用8个字节),又如,一个元素类型为 complex32 的数组 item 属性为 4(32/8)
import numpy as np # 数组的 dtype 为 int8(一个字节) x = np.array([1,2,3,4,5], dtype = np.int8) print (x.itemsize) # 数组的 dtype 现在为 float64(八个字节) y = np.array([1,2,3,4,5], dtype = np.float64) print (y.itemsize) #结果 1 8
ndarray.flags返回ndarray对象的内存信息,包含以下属性:
C_CONTIGUOUS (C) | 数据是在一个单一的C风格的连续段中 |
F_CONTIGUOUS (F) | 数据是在一个单一的Fortran风格的连续段中 |
OWNDATA (O) | 数组拥有它所使用的内存或从另一个对象中借用它 |
WRITEABLE (W) | 数据区域可以被写入,将该值设置为 False,则数据为只读 |
ALIGNED (A) | 数据和所有元素都适当地对齐到硬件上 |
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 WRITEBACKIFCOPY : False UPDATEIFCOPY : False
Numpy创建数组
numpy.empty方法用来创建一个指定形状(shape)、数据类型(dtype)且未初始化的数组:
numpy.empty(shape, dtype = float, order = 'C')
shape | 数组形状 |
dtype | 数据类型,可选 |
order | 有"C"和"F"两个选项,分别代表,行优先和列优先,在计算机内存中的存储元素的顺序。 |
#创建空数组的实例 import numpy as np x = np.empty([3,2], dtype=int) #结果 [[0,0], [0,0] [0,0]]
numpy.zeros 创建指定大小的数组,数组元素以0来补充
numpy.zeros(shape, dtype = float, order = 'C')
shape | 数组形状 |
dtype | 数据类型,可选 |
order | 'C' 用于 C 的行数组,或者 'F' 用于 FORTRAN 的列数组 |
import numpy as np # 默认为浮点数 x = np.zeros(5) print(x) # 设置类型为整数 y = np.zeros((5,), dtype = np.int) print(y) # 自定义类型 z = np.zeros((2,2), dtype = [('x', 'i4'), ('y', 'i4')]) print(z) #结果 [0. 0. 0. 0. 0.] [0 0 0 0 0] [[(0, 0) (0, 0)] [(0, 0) (0, 0)]]
numpy.ones创建指定形状的数组,数组元素以1来填充
numpy.ones(shape, dtype = None, order = 'C')
shape | 数组形状 |
dtype | 数据类型,可选 |
order | 'C' 用于 C 的行数组,或者 'F' 用于 FORTRAN 的列数组 |
import numpy as np # 默认为浮点数 x = np.ones(5) print(x) # 自定义类型 x = np.ones([2,2], dtype = int) print(x) #结果 [1. 1. 1. 1. 1.] [[1 1] [1 1]]
Numpy从已有的数组创建数组
numpy.asarray类似numpy.array,但numpy.asarray参数只有三个,比numpy.array少两个
numpy.asarray(a, dtype = None, order = None)
a | 任意形式的输入参数,可以是,列表, 列表的元组, 元组, 元组的元组, 元组的列表,多维数组 |
dtype | 数据类型,可选 |
order | 可选,有"C"和"F"两个选项,分别代表,行优先和列优先,在计算机内存中的存储元素的顺序。 |
import numpy as np x = [1,2,3] a = np.asarray(x) print (a) #结果 [1 2 3]
import numpy as np x = (1,2,3) a = np.asarray(x) print (a) #结果 [1 2 3]
import numpy as np x = [(1,2,3),(4,5)] a = np.asarray(x) print (a) #结果 [(1,2,3)(4,5)]
import numpy as np x = [1,2,3] a = np.asarray(x, dtype = float) print (a) #结果 [1. 2. 3.]
numpy.frombuffer
numpy.frombuffer用于实现动态数组
numpy.frombuffer接受buffer输入参数,以流动的形式读入转化成 ndarray 对象
numpy.frombuffer(buffer, dtype = float, count = -1, offset = 0)
注意:buffer 是字符串的时候,Python3 默认 str 是 Unicode 类型,所以要转成 bytestring 在原 str 前加上 b。
buffer | 可以是任意对象,会以流的形式读入。 |
dtype | 返回数组的数据类型,可选 |
count | 读取的数据数量,默认为-1,读取所有数据。 |
offset | 读取的起始位置,默认为0。 |
import numpy as np s = b'Hello World' a = np.frombuffer(s, dtype='S1') print(a) #结果 [b'H' b'e' b'l' b'l' b'o' b' ' b'W' b'o' b'r' b'l' b'd']
numpy.fromiter方法从可跌代对象中建立ndarray对象,返回一维数组
numpy.fromiter(iterable, dtype, count=-1)
iterable | 可迭代对象 |
dtype | 返回数组的数据类型 |
count | 读取的数据数量,默认为-1,读取所有数据 |
import numpy as np # 使用 range 函数创建列表对象 list=range(5) it=iter(list) # 使用迭代器创建 ndarray x=np.fromiter(it, dtype=float) print(x) #结果 [0. 1. 2. 3. 4. ]