numpy中的ndarray

279 阅读3分钟

这是我参与11月更文挑战的第6天,活动详情查看:2021最后一次更文挑战

环境

  • ubuntu 18.04 64bit
  • numpy 1.19.2

简介

numpypython 中的一个数值计算的开源库,主要用来存储和处理多维数组,核心数据结构是 ndarray。本文分享 ndarray 的基本使用, 首先需要安装 numpy

pip install numpy

二维ndarray

要构造二维数组(就是矩阵),需要知道数组的行数、列数和每个元素的数据类型,在 numpy 中,常见的有uint8int32float32float64等等

下面构造一个2行3列全是0的 uint8 类型的二维数组

(base) xugaoxiang@1070Ti:~$ ipython
Python 3.7.6 (default, Jan  8 2020, 19:59:22)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.19.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: import numpy as np

In [2]: np.zeros((2, 3), np.uint8)
Out[2]:
array([[0, 0, 0],
       [0, 0, 0]], dtype=uint8)

In [3]:

如果想构造全是1的数组,可以使用 np.ones() 方法

In [5]: np.ones((2, 3), np.uint8)
Out[5]:
array([[1, 1, 1],
       [1, 1, 1]], dtype=uint8)

使用常量数据进行初始化

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

三维ndarray

三维数组可以理解为每一个元素都是一个二维数组。比如一个2x2x3的 uint8 三维数组,就是2个2x3的二维数组

In [11]: np.array([[[1, 2, 3], [4, 5, 6]], [[9, 8, 7], [6, 5, 4]]], np.uint8)
Out[11]:
array([[[1, 2, 3],
        [4, 5, 6]],

       [[9, 8, 7],
        [6, 5, 4]]], dtype=uint8)

In [12]:

了解了这个原理后,以此类推,更高维的数组就很好理解了

ndarray的常用属性及元素值获取

shape属性可以获取到尺寸,比如

In [12]: t = np.zeros([2, 3], np.uint8)

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

In [14]:

In [14]: t3 = np.array([[[1, 2, 3], [4, 5, 6]], [[9, 8, 7], [6, 5, 4]]],np.uint8
    ...: )

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

In [16]:

dtype 属性可以获取到元素的数据类型,如

In [17]: t.dtype
Out[17]: dtype('uint8')

In [18]: t3.dtype
Out[18]: dtype('uint8')

In [19]:

获取数组中某个元素的值,可以通过索引来获取,索引从0开始计算,以二维为例

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

In [21]: t[1, 1]
Out[21]: 5

In [22]: t[0, 2]
Out[22]: 3

In [23]:

获取某行数据,以上面的 t 变量为例,代码如下

In [36]: t[0,:]
Out[36]: array([1, 2, 3], dtype=uint8)

In [37]: t[1,:]
Out[37]: array([4, 5, 6], dtype=uint8)

# 当索引超出后,会报错
In [38]: t[2,:]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-38-79ac94a5bef6> in <module>
----> 1 t[2,:]

IndexError: index 2 is out of bounds for axis 0 with size 2

In [39]:

获取某列数据,以上面的 t 变量为例,代码如下

In [40]: t[:,0]
Out[40]: array([1, 4], dtype=uint8)

In [41]: t[:,1]
Out[41]: array([2, 5], dtype=uint8)

In [42]: t[:,2]
Out[42]: array([3, 6], dtype=uint8)

In [43]: t[:,3]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-43-cd95ba35026b> in <module>
----> 1 t[:,3]

IndexError: index 3 is out of bounds for axis 1 with size 3

In [44]:

除此之外,还可以获取到某一区间,代码如下

# 这里的区间操作是左闭右开的,如[0:1],就是从0行开始,但不包括第1行
In [45]: t[0:1,1:3]
Out[45]: array([[2, 3]], dtype=uint8)

In [46]: