数组的属性
数组属性反映了数组本身固有的信息。通常,通过其属性访问数组允许您获取或者设置数组的内在属性,而无需创建新数组。属性是数组的核心部分,其中一些可以重置,无需创建新数组。数组的属性可以分为内存布局属性,数据类型属性,其他属性。
内存布局属性
以下属性包含有关数组内存布局的信息:
属性名 | 说明 |
---|---|
ndarray.flags | 数组内存布局的信息 |
ndarray.shape | 数组的形状,返回元组 |
ndarray.strides | 遍历数组时要在每个维度中步进的字节元组 |
ndarray.ndim | 维度,维数,轴数,秩 |
ndarray.data | 指向数组数据开头的 Python 缓冲区对象。 |
ndarray.size | 数组中元素的个数 |
ndarray.itemsize | 数组中元素占用的长度(字节为单位) |
ndarray.nbytes | 数组元素占用的总字节数 |
ndarray.base | 如果内存来自其他对象,则为基础对象。 |
ndarray.shape
>>> import numpy as np
>>> a = np.zeros(shape=(2, 3), dtype=np.int8) # 创建数组
array([[0, 0, 0],
[0, 0, 0]], dtype=int8)**
>>> a.shape # 数组a的形状,返回一个元组(行数,列数),
(2, 3)
注意:一维数组的形状也是一个元组,形如:(6,)。
ndarray.ndim
>>> import numpy as np
>>> a = np.zeros(shape=(2, 3), dtype=np.int8) # 创建数组
array([[0, 0, 0],
[0, 0, 0]], dtype=int8)
>>> a.ndim # 数组a的维度(也称为维数,轴数,秩)两个轴,行、列
2
ndarray.size
>>> import numpy as np
>>> a = np.zeros(shape=(2, 3), dtype=np.int8) # 创建数组
array([[0, 0, 0],
[0, 0, 0]], dtype=int8)
>>> a.size # 数组a中的元素个数
6
ndarray.itemsize
>>> import numpy as np
>>> a = np.zeros(shape=(2, 3), dtype=np.int8) # 创建数组
array([[0, 0, 0],
[0, 0, 0]], dtype=int8)
>>> a.itemsize # 数组a中元素占用的字节数,与元素的数据类型dtype相关
1
ndarray.nbytes
>>> import numpy as np
>>> a = np.zeros(shape=(2, 3), dtype=np.int8) # 创建数组
array([[0, 0, 0],
[0, 0, 0]], dtype=int8)
>>> a.nbytes # 数组a占用的字节数,nbytes = itemsize * size
6
ndarray.flags
>>> import numpy as np
>>> a = np.zeros(shape=(2, 3), dtype=np.int8) # 创建数组
array([[0, 0, 0],
[0, 0, 0]], dtype=int8)
>>> a.flags # 数组内存布局信息
C_CONTIGUOUS : True
F_CONTIGUOUS : False
OWNDATA : True
WRITEABLE : True
ALIGNED : True
WRITEBACKIFCOPY : False
UPDATEIFCOPY : False
数据类型属性
属性名 | 说明 |
---|---|
ndarray.dtype | 数组中元素的数据类型 |
ndarray.dtype
>>> import numpy as np
>>> a = np.zeros(shape=(2, 3), dtype=np.int8) # 创建数组
array([[0, 0, 0],
[0, 0, 0]], dtype=int8)
>>> a.dtype # 数组元素的数据类型
dtype('int8')
其他属性
属性名 | 说明 |
---|---|
ndarray.T | 数组转置 |
ndarray.real | 数组复数的实部 |
ndarray.imag | 数组复数的虚部 |
ndarray.flat | 数组的一维迭代器 |
ndarray.T
>>> import numpy as np
>>> a = np.zeros(shape=(2, 3), dtype=np.int8) # 创建数组
array([[0, 0, 0],
[0, 0, 0]], dtype=int8)
>>> a.T # 数组a的转置,行列交换
array([[0, 0],
[0, 0],
[0, 0]], dtype=int8)
ndarray.flat
>>> import numpy as np
>>> a = np.zeros(shape=(2, 3), dtype=np.int8) # 创建数组
array([[0, 0, 0],
[0, 0, 0]], dtype=int8)
>>> a.flat # 将高维数组变为一维,返回flatiter的内存地址
<numpy.flatiter at 0x1d7090eaec0>
以上示例讲解了常用的数组属性