牛骨文教育服务平台(让学习变的简单)
博文笔记

Numpy数组属性

创建时间:2018-01-31 投稿人: 浏览次数:720

      • 数组对象的属性
        • shape
          • 示例 1
          • 示例 2
          • 示例 3
        • ndim
          • 示例 1
        • size
          • 示例
        • itemsize
          • 示例 1
          • 示例 2
        • flags
          • 示例
        • imag
        • real
      • dtype 加深
        • 数据类型对象
        • 类型转换

数组对象的属性

属性 说明
.ndim 秩,即轴的数量或维度的数量
.shape ndarray对象的尺度,对于矩阵,n行m列
.size ndarray对象元素的个数,相当于.shape中n*m的值
.dtype ndarray对象的元素类型
.itemsize ndarray对象中每个元素的大小,以字节为单位
.flags ndarray对象的内存信息
.real ndarray元素的实部
.image ndarray元素的虚部

.shape

这一数组属性返回一个包含数组维度的元组,它也可以用于调整数组大小。

示例 1
In [1]: import numpy as np

In [2]: a = np.array([[1,2,3],[4,5,6]])

In [3]: a.shape
Out[3]: (2, 3)
示例 2
# 这会调整数组大小  
In [1]: import numpy as np              

In [2]: a = np.array([[1,2,3],[4,5,6]]) 

In [3]: a.shape                         
Out[3]: (2, 3)                          

In [4]: a.shape =  (3,2)                

In [5]: a                               
Out[5]:                                 
array([[1, 2],                          
       [3, 4],                          
       [5, 6]])                         
示例 3

NumPy 也提供了reshape函数来调整数组大小。

In [7]: import numpy as np

In [8]: a = np.array([[1,2,3],[4,5,6]])

In [9]: b = a.reshape(6,1)

In [10]: b
Out[10]:
array([[1],
       [2],
       [3],
       [4],
       [5],
       [6]])

.ndim

这一数组属性返回数组的维数。

示例 1
# 等间隔数字的数组  
In [11]: import numpy as np

In [12]: a = np.arange(24)

In [13]: a.ndim
Out[13]: 1

In [14]: a
Out[14]:
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
       17, 18, 19, 20, 21, 22, 23])

In [15]: b = a.reshape(2,3,4)

In [16]: b.ndim
Out[16]: 3

In [17]: b
Out[17]:
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]],

       [[12, 13, 14, 15],
        [16, 17, 18, 19],
        [20, 21, 22, 23]]])

.size

这一数组属性返回数组中元素个数。

示例
In [36]: a = np.arange(24)                                                 

In [37]: a                                                                 
Out[37]:                                                                   
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 
       17, 18, 19, 20, 21, 22, 23])                                        

In [38]: a.size                                                            
Out[38]: 24                                                                

.itemsize

这一数组属性返回数组中每个元素的字节单位长度。

示例 1
# 数组的 dtype 为 int8(一个字节)  
In [18]: import numpy as np

In [19]: x = np.array([1,2,3,4,5], dtype = np.int8)

In [20]: x.itemsize
Out[20]: 1
示例 2
# 数组的 dtype 现在为 float32(四个字节)  
In [21]: import numpy as np

In [22]: x = np.array([1,2,3,4,5], dtype = np.float32)

In [23]: x.itemsize
Out[23]: 4

.flags

ndarray对象拥有以下属性。这个函数返回了它们的当前值。

序号 属性及描述
1. C_CONTIGUOUS (C) 数组位于单一的、C 风格的连续区段内
2. F_CONTIGUOUS (F) 数组位于单一的、Fortran 风格的连续区段内
3. OWNDATA (O) 数组的内存从其它对象处借用
4. WRITEABLE (W) 数据区域可写入。 将它设置为flase会锁定数据,使其只读
5. ALIGNED (A) 数据和任何元素会为硬件适当对齐
6. UPDATEIFCOPY (U) 这个数组是另一数组的副本。当这个数组释放时,源数组会由这个数组中的元素更新
示例

下面的例子展示当前的标志。

In [27]: import numpy as np

In [28]: x = np.array([1,2,3,4,5])

In [29]: x.flags
Out[29]:
  C_CONTIGUOUS : True
  F_CONTIGUOUS : True
  OWNDATA : True
  WRITEABLE : True
  ALIGNED : True
  UPDATEIFCOPY : False

.imag

ndarray.imag 用来输出数组包含元素的虚部。

.real

ndarray.real用来输出数组包含元素的实部。

In [9]: import numpy as np                                                   

In [10]: a = np.arange(12)                                                   

In [11]: b = np.array(a,dtype=np.complex)                                    

In [12]: b                                                                   
Out[12]:                                                                     
array([  0.+0.j,   1.+0.j,   2.+0.j,   3.+0.j,   4.+0.j,   5.+0.j,           
         6.+0.j,   7.+0.j,   8.+0.j,   9.+0.j,  10.+0.j,  11.+0.j])          

In [13]: b.imag                                                              
Out[13]: array([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.]) 

In [14]: b.real                                                              
Out[14]:                                                                     
array([  0.,   1.,   2.,   3.,   4.,   5.,   6.,   7.,   8.,   9.,  10.,     
        11.])                                                                

dtype 加深

NumPy 支持比 Python更多种类的数值类型。 下表显示了 NumPy 中定义的不同标量数据类型。

序号 数据类型及描述
bool 存储为一个字节的布尔值(真或假),字符代码b
int 默认整数,相当于 C 的long,通常为int32或int64,字符代码i
intc 相当于 C 的int,通常为int32或int64,字符代码i
intp intp用于索引的整数,相当于 C 的size_t,通常为int32或int64,字符代码i
int8 8字节(-128 ~ 127),字符代码i
int16 16 位整数(-32768 ~ 32767),字符代码i
int32 32 位整数(-2147483648 ~ 2147483647),字符代码i
int64 64 位整数(-9223372036854775808 ~ 9223372036854775807),字符代码i
uint8 8 位无符号整数(0 ~ 255),字符代码u
uint16 16 位无符号整数(0 ~ 65535),字符代码u
uint32 32 位无符号整数(0 ~ 4294967295),字符代码u
uint64 64 位无符号整数(0 ~ 18446744073709551615),字符代码u
float float64的简写,字符代码f
float16 float16半精度浮点:符号位,5 位指数,10 位尾数,字符代码f
float32 float32单精度浮点:符号位,8 位指数,23 位尾数,字符代码f
float64 float64双精度浮点:符号位,11 位指数,52 位尾数,字符代码f
complex complex_complex128的简写,字符代码c
complex64 complex64复数,由两个 32 位浮点表示(实部和虚部),字符代码c
complex128 complex128复数,由两个 64 位浮点表示(实部和虚部),字符代码c
object 非同质的ndarray对象,元素为对象类型。 非同质ndarray对象无法有效发挥NumPy优势,尽量避免使用。字符代码O

其他的字符代码:

  • m:时间间隔
  • M:日期时间
  • U:Unicode
  • V:原始数据(void)

数据类型对象

  • 数据类型对象描述了对应于数组的固定内存块的解释,取决于以下方面:
    • 数据类型(整数、浮点或者 Python对象)
    • 数据大小
    • 字节序(小端或大端)
      • <意味着编码是小端(最小有效字节存储在最小地址中)。
      • >意味着编码是大端(最大有效字节存储在最小地址中)。
    • 在结构化类型的情况下,字段的名称,每个字段的数据类型,和每个字段占用的内存块部分。
    • 如果数据类型是子序列,它的形状和数据类型。

dtype可由一下语法构造:

numpy.dtype(object, align, copy)

参数为:

  • Object: 被转换为数据类型的对象。
  • Align: 如果为true,则向字段添加间隔,使其类似 C的结构体。
  • Copy: 生成dtype对象的新副本,如果为flase,结果是内建数据类型对象的引用。

  • 使用数组标量类型

    In [16]: import numpy as np
    
    In [17]: dt = np.dtype(np.int32)
    
    In [18]: dt
    Out[18]: dtype("int32")
  • int8,int16,int32,int64 可替换为等价的字符串 ‘i1’,’i2’,’i4’,以及其他。

    In [19]: import numpy as np
    
    In [20]: dt = np.dtype("i4")
    
    In [21]: dt
    Out[21]: dtype("int32")
  • 使用端记号

    In [22]: import numpy as np
    
    In [23]: dt = np.dtype(">i4")
    
    In [24]: dt
    Out[24]: dtype(">i4")
  • 简单结构化数据类型

    
    # 首先创建结构化数据类型。  
    
    In [25]: import numpy as np
    
    In [26]: dt = np.dtype([("age",np.int8)])
    
    In [27]: dt
    Out[27]: dtype([("age", "i1")])
    
    # 现在将其应用于 ndarray 对象  
    
    In [28]: import numpy as np
    
    In [29]: dt = np.dtype([("age",np.int8)])
    
    In [30]: a = np.array([(10,),(20,),(30,)],dtype = dt)
    
    In [31]: a
    Out[31]:
    array([(10,), (20,), (30,)],
          dtype=[("age", "i1")])
    
    
    # 文件名称可用于访问 age 列的内容  
    
    In [32]: a["age"]
    Out[32]: array([10, 20, 30], dtype=int8)
  • 复杂结构化数据类型

    以下示例定义名为 student 的结构化数据类型,其中包含字符串字段name整数字段age浮点字段marks。 此dtype应用于ndarray对象。

    In [33]: import numpy as np
    
    In [34]: student = np.dtype([("name","S20"),  ("age",  "i1"),  ("marks",  "f4")])
    
    In [35]: student
    Out[35]: dtype([("name", "S20"), ("age", "i1"), ("marks", "<f4")])
    
    In [33]: import numpy as np
    
    In [34]: student = np.dtype([("name","S20"),  ("age",  "i1"),  ("marks",  "f4")])
    
    In [35]: student
    Out[35]: dtype([("name", "S20"), ("age", "i1"), ("marks", "<f4")])
    
    In [36]: a = np.array([("abc",  21,  50),("xyz",  18,  75)], dtype = student)
    
    In [37]: a
    Out[37]:
    array([(b"abc", 21, 50.0), (b"xyz", 18, 75.0)],
          dtype=[("name", "S20"), ("age", "i1"), ("marks", "<f4")])

类型转换

既然Numpy数组是静态类型,数组一旦生成类型就无法改变。但是我们可以显示地对某些元素数据类型进行转换生成新的数组,使用 astype 函数(可查看功能相似的 asarray 函数):

In [43]: import numpy as np

In [44]: atInt = np.array([[1., 4.], [9., 16.]], dtype=np.int32)

In [45]: atInt
Out[45]: 
array([[ 1,  4],
       [ 9, 16]], dtype=int32)

In [46]: toFloat = atInt.astype(float)

In [47]: toFloat
Out[47]: 
array([[  1.,   4.],
       [  9.,  16.]])

In [48]: toBool = atInt.astype(bool)

In [49]: toBool
Out[49]: 
array([[ True,  True],
       [ True,  True]], dtype=bool)

numpy中,还有一系列以 as 开头的方法,它们可以将特定输入转换为数组,亦可将数组转换为矩阵、标量,ndarray等。如下:

  • asarray(a,dtype,order):将特定输入转换为数组。
  • asanyarray(a,dtype,order):将特定输入转换为 ndarray
  • asmatrix(data,dtype):将特定输入转换为矩阵。
  • asfarray(a,dtype):将特定输入转换为 float 类型的数组。
  • asarray_chkfinite(a,dtype,order):将特定输入转换为数组,检查 NaNinfs
  • asscalar(a):将大小为 1 的数组转换为标量。

这里以 asmatrix(data,dtype) 方法举例:

In [50]: a = np.arange(4).reshape(2,2)

In [51]: np.asmatrix(a)
Out[51]: 
matrix([[0, 1],
        [2, 3]])
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。