5.NumPy数组属性

本节介绍 Numpy 数组的常用属性。

ndarray.shape

shape 属性的返回值一个由数组维度构成的元组,比如 2 行 3 列的二维数组可以表示为(2,3),该属性可以用来调整数组维度的大小。

示例如下,输出了数组的维度:

  1. import numpy as np
  2. a = np.array([[2,4,6],[3,5,7]])
  3. print(a.shape)

输出结果:

(2,3)

通过 shape 属性修改数组的形状大小: 

  1. import numpy as np
  2. a = np.array([[1,2,3],[4,5,6]])
  3. a.shape = (3,2)
  4. print(a)

输出结果:

  1. [[1, 2]
  2. [3, 4]
  3. [5, 6]]

ndarray.reshape()

NumPy 还提供了一个调整数组形状的 reshape() 函数。

  1. import numpy as np
  2. a = np.array([[1,2,3],[4,5,6]])
  3. b = a.reshape(3,2)
  4. print(b)

输出结果:

[[1, 2]
[3, 4]
[5, 6]]

ndarray.ndim

该属性返回的是数组的维数,示例如下:

  1. import numpy as np
  2. #随机生成一个一维数组
  3. c = np.arange(24)
  4. print(c)
  5. print(c.ndim)
  6. #对数组进行变维操作
  7. e = c.reshape(2,4,3)
  8. print(e)
  9. print(e.ndim)

输出结果如下所示:

#随机生成的c数组
[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23]
#c数组的维度
1
#变维后数组e
[[[ 0  1  2]
  [ 3  4  5]
  [ 6  7  8]
  [ 9 10 11]]

[[12 13 14]
  [15 16 17]
  [18 19 20]
  [21 22 23]]]
#e的数组维度
3

ndarray.itemsize

返回数组中每个元素的大小(以字节为单位),示例如下:

  1. #数据类型为int8,代表1字节
  2. import numpy as np
  3. x = np.array([1,2,3,4,5], dtype = np.int8)
  4. print (x.itemsize)

输出结果为:

1

  1. #数据类型为int64,代表8字节
  2. import numpy as np
  3. x = np.array([1,2,3,4,5], dtype = np.int64)
  4. print (x.itemsize)

输出结果:

8

ndarray.flags

返回 ndarray 数组的内存信息,比如 ndarray 数组的存储方式,以及是否是其他数组的副本等。

示例如下:

  1. import numpy as np
  2. x = np.array([1,2,3,4,5])
  3. print (x.flags)

输出结果如下:

C_CONTIGUOUS : True
F_CONTIGUOUS : True
OWNDATA : True
WRITEABLE : True
ALIGNED : True
WRITEBACKIFCOPY : False
UPDATEIFCOPY : False
posted @ 2022-08-02 16:28  随遇而安==  阅读(25)  评论(0编辑  收藏  举报