numpy 创建数组

创建数组的方式有很多种,比如使用array方法,并提供标准的Python列表或者元组作为参数。此时,数组的类型将根据序列中元素的类型推导出来。

>>> import numpy as np
>>> a = np.array([2,3,4])
>>> a
array([2, 3, 4])
>>> a.dtype
dtype('int32')
>>> b = np.array([1.2, 3.5, 5.1])
>>> b.dtype
dtype('float64')

常见的错误是直接将多个数值作为参数传递,正确的做法是将他们以列表或元组的方式传递,如下:

>>> a = np.array(1,2,3,4)    # 错误
>>> a = np.array([1,2,3,4])  # 正确

array函数会自动将二维或三维序列转换为对应的二维或三维数组。

>>> b = np.array([(1.5,2,3), (4,5,6)])
>>> b
array([[ 1.5,  2. ,  3. ],
       [ 4. ,  5. ,  6. ]])

在创建的时候,可以显式地指定数据的类型:

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

那么我们只能玩数字么?不是的,字符串也可以,只是我们不常用而已:

>>> s = 'hellow world'
>>> np.array(s)
array('hellow world', dtype='<U12')

很多时候,数组的元素最初都是未知的,但其大小形状是已知的。因此,numpy提供了几个函数来创建带有初始占位符内容的数组。

函数zero创建一个都是0的数组,函数one创建一个都是1的数组,函数empty创建一个初始内容是0或者垃圾值的数组,这取决于内存当时的状态。默认情况下,创建的数组的数据类型为float64。

>>> np.zeros((5,), dtype = np.float)
array([0., 0., 0., 0., 0.])
>>> np.zeros( (3,4) )
array([[ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.]])
>>> np.ones( (2,3,4), dtype=np.int16 )                # 同样可以指定类型
array([[[ 1, 1, 1, 1],
        [ 1, 1, 1, 1],
        [ 1, 1, 1, 1]],
       [[ 1, 1, 1, 1],
        [ 1, 1, 1, 1],
        [ 1, 1, 1, 1]]], dtype=int16)
>>> np.empty( (2,3) )   # 根据当前内存状态的不同,可能会返回未初始化的垃圾数值,不安全。
array([[0., 0., 0.],
       [0., 0., 0.]])

>>> np.full((3,4), 2.22) # 创建一个全部由2.22组成的数组
array([[2.22, 2.22, 2.22, 2.22],
       [2.22, 2.22, 2.22, 2.22],
       [2.22, 2.22, 2.22, 2.22]])

numpy还提供了一个返回array序列的函数,而不是返回一个Python的列表,这就是常用的arange函数:

>>> np.arange( 10, 30, 5 )
array([10, 15, 20, 25])
>>> np.arange( 0, 2, 0.3 )                 # 可以接受浮点类型的参数,比如这里的步长
array([ 0. ,  0.3,  0.6,  0.9,  1.2,  1.5,  1.8])

其原型为:

numpy.arange(start, stop, step, dtype)
  1. start:范围的起始值,默认为0
  2. stop: 范围的终止值(不包含)
  3. step: 两个值的间隔,默认为1
  4. dtype: 返回ndarray的数据类型,如果没有提供,则会使用输入数据的类型。

当arange函数使用浮点步长的时候,可能出现精度的问题。这种情况下,我们一般使用linspace函数,它的第三个参数指定在区间内均匀生成几个数,至于步长,系统会自动计算。

>>> from numpy import pi  # 导入圆周率
>>> np.linspace( 0, 2, 9 )                 # 从0到2之间的9个数
array([ 0.  ,  0.25,  0.5 ,  0.75,  1.  ,  1.25,  1.5 ,  1.75,  2.  ])
>>> x = np.linspace( 0, 2*pi, 100 )        # 从0到2Π之间,生成100个数
>>> f = np.sin(x)

其原型为:

numpy.linspace(start, stop, num, endpoint, retstep, dtype)
  1. start: 序列的起始值
  2. stop: 序列的终止值,如果endpoint为True,则终止值包含于序列中
  3. num: 要生成的等间隔样例数量,默认为50
  4. endpoint: 序列中是否包含stop值,默认为Ture
  5. retstep: 如果为True,返回样例以及连续数字之间的步长
  6. dtype: 输出ndarray的数据类型

更多类似的函数有:array, zeros, zeros_like, ones, ones_like, empty, empty_like, arange, linspace, numpy.random.rand, numpy.random.randn, fromfunction, fromfile