Lesson2——NumPy Ndarray 对象

NumPy 教程目录

NumPy Ndarray 对象

  NumPy 最重要的一个特点是其 $N$ 维数组对象 ndarray,它是一系列同类型数据的集合,以 $0$ 下标为开始进行集合中元素的索引。

  ndarray 对象是用于存放同类型元素多维数组

  ndarray 中的每个元素在内存中都有相同存储大小的区域

  ndarray 内部由以下内容组成:

    • 一个指向数据(内存或内存映射文件中的一块数据)的指针。

    • 数据类型或 dtype,描述在数组中的固定大小值的格子。

    • 一个表示数组形状(shape)的元组,表示各维度大小的元组。

    • 一个跨度元组(stride),其中的整数指的是为了前进到当前维度下一个元素需要"跨过"的字节数。

  ndarray 的内部结构:

  

  跨度可以是负数,这样会使数组在内存中后向移动,切片中 obj[::-1] 或 obj[:,::-1] 就是如此。

  创建一个 ndarray 只需调用 NumPy.array() 函数即可:

numpy.array(object, dtype = None, copy = True, order = None, subok = False, ndmin = 0)

  参数说明:

名称描述
object 数组或嵌套的数列
dtype 数组元素的数据类型,可选
copy 对象是否需要复制,可选
order 创建数组的样式,C为行方向,F为列方向,A为任意方向(默认)
subok 默认返回一个与基类类型一致的数组
ndmin 指定生成数组的最小维度

  See also

    • empty_like Return an empty array with shape and type of input.
    • ones_like Return an array of ones with shape and type of input.
    • zeros_like Return an array of zeros with shape and type of input.
    • full_like Return a new array with shape of input filled with value.
    • empty Return a new uninitialized array.
    • ones Return a new array setting values to one.
    • zeros Return a new array setting values to zero.
    • full Return a new array of given shape filled with value.

  这里提供一些关于 NumPy.array() 的例子:

  Examples 1:

>>> np.array([1, 2, 3])
array([1, 2, 3])

  Examples 2:

>>> np.array([1, 2, 3.0])
array([ 1.,  2.,  3.])

  Examples 3:More than one dimension:

>>> np.array([[1, 2], [3, 4]])
array([[1, 2],
       [3, 4]])

  Examples 4:Minimum dimensions 2:

>>> np.array([1, 2, 3], ndmin=2)
array([[1, 2, 3]])

  Examples 5:Type provided:

>>> np.array([1, 2, 3], dtype=complex)
array([ 1.+0.j,  2.+0.j,  3.+0.j])

  Examples 6:Data-type consisting of more than one element:

>>> x = np.array([(1,2),(3,4)],dtype=[('a','<i4'),('b','<i4')])
>>> x['a']
array([1, 3])

  Examples 7:Creating an array from sub-classes:

>>> np.array(np.mat('1 2; 3 4'))
array([[1, 2],
       [3, 4]])

>>> np.array(np.mat('1 2; 3 4'), subok=True)
matrix([[1, 2],
        [3, 4]])

 

posted @ 2022-02-07 17:19  多发Paper哈  阅读(65)  评论(0编辑  收藏  举报
Live2D