Numpy narray对象的属性分析
narray是Numpy的基本数据结构,本文主要分析对象的属性(可通过.进行访问)
1:导入numpy:
import numpy as np
2:初始化narray对象:
>>> x = np.array([[1, 2, 3], [4, 5, 6]], np.int32) >>> x array([[1, 2, 3], [4, 5, 6]], dtype=int32)
3:查看np对象的行列sharp(np.shape)(返回两个元素元组,分别是行,列.):
>>> x.shape
(2, 3)
4:查看np对象的内存布局(np.flags)(详情点这里):
>>> x.flags
C_CONTIGUOUS : True :The data is in a single, C-style contiguous segment.
F_CONTIGUOUS : False :The data is in a single, Fortran-style contiguous segment.
OWNDATA : True :The array owns the memory it uses or borrows it from another object.
WRITEABLE : True :The data area can be written to.
ALIGNED : True :The data and all elements are aligned appropriately for the hardware.
UPDATEIFCOPY : False :(Deprecated, use WRITEBACKIFCOPY) This array is a copy of some other array. When this array is deallocated, the base array will be updated with the contents of this array.
5:查看数组的大小:(np.size)(即所有元素个数Number of elements in the array.):
>>> x.size
6
6:遍历数组时,在每个维度中步进的字节数组(np.strides)(Tuple of bytes to step in each dimension when traversing an array.):
>>> x array([[1, 2, 3], [4, 5, 6]], dtype=int32) >>> x.strides (12, 4) 以本片代码为例:int32位占据4个字节的数据,因此同行内移动一个数据至相邻的列需要4个字节,移动到下一行相同列需要(元素大小4*列数3)12个字节 >>> x = np.array([[1, 2, 3], [4, 5, 6]], np.int64) >>> x.strides (24, 8)
7:查看数组维度(np.ndim)(Number of array dimensions.):
>>> x.ndim
2
8:查看数组内存缓冲区的开始位置(np.data)(Python buffer object pointing to the start of the array’s data.):
>>> x.data
<memory at 0x7f49c189a990>
9:查看数组每一个元素所占的内存大小(np.itemsize)(Length of one array element in bytes.):
>>> x = np.array([1, 2], np.complex128) >>> x.itemsize 16 >>> x = np.array([1, 2], np.int16) >>> x.itemsize
10:查看数组元素消耗的总字节(np.nbytes)(Total bytes consumed by the elements of the array.):
>>> x = np.array([1, 2], np.int16)
>>> x.nbytes
4
11:查看数组的基对象(np.base)(Base object if memory is from some other object.)
>>> x = np.array([[1, 2, 3], [4, 5, 6]], np.int64) >>> x.base >>> y = x[1:] (分片后的对象与原对象共享内存) >>> y.base array([[1, 2, 3], [4, 5, 6]])
请以官方文档为准,有问题可以留言,