numpy基础(1)

numpy是python中常用的有关科学计算的包,主要提供了创建各种类型的数组和数组运算,以及各类线性代数,傅里叶变换,随机数生成等方法。

NumPy数组对象

ndarray是numpy中一个多维数组对象,该对象由两部分组成:实际的数据加上描述数据的元数据

数据的属性:

  • shape,返回数组的形状
  • dtype,返回数组中各元素的类型
  • ndim,返回数组的维数或数组轴的个数(有多少对[]就有多少维数)
  • size,返回数组元素的总个数
  • itemsize,返回数组中元素在内存中所占的字节数
  • nbyte,返回数组所占的存储空间,即itemsize和size的乘积
  • T,返回数组的转置数组
  • flat,返回一个numpy.flatiter对象,即展平迭代器。可以像遍历一维数组一样去遍历任意多维数组,也可从迭代器中获取指定的数组元素(flat是一个可赋值的属性)

一维数组

创建一维数组

>>> import numpy as np
>>> a=np.arange(4)
>>> a
array([0, 1, 2, 3])
>>> a=np.arange(1,5,2)
>>> a
array([1, 3])
>>> a.dtype
dtype('int32')
>>> a.shape
(2,)

可以通过help查找指定函数的用法:

print(help(np.arange))
Help on built-in function arange in module numpy.core.multiarray:

arange(...)
    arange([start,] stop[, step,], dtype=None)
    
    Return evenly spaced values within a given interval.
    
    Values are generated within the half-open interval ``[start, stop)``
    (in other words, the interval including `start` but excluding `stop`).
    For integer arguments the function is equivalent to the Python built-in
    `range <http://docs.python.org/lib/built-in-funcs.html>`_ function,
    but returns an ndarray rather than a list.
    
    When using a non-integer step, such as 0.1, the results will often not
    be consistent.  It is better to use ``linspace`` for these cases.
    
    Parameters
    ----------
    start : number, optional
        Start of interval.  The interval includes this value.  The default
        start value is 0.
    stop : number
        End of interval.  The interval does not include this value, except
        in some cases where `step` is not an integer and floating point
        round-off affects the length of `out`.
    step : number, optional
        Spacing between values.  For any output `out`, this is the distance
        between two adjacent values, ``out[i+1] - out[i]``.  The default
        step size is 1.  If `step` is specified as a position argument,
        `start` must also be given.
    dtype : dtype
        The type of the output array.  If `dtype` is not given, infer the data
        type from the other input arguments.
    
    Returns
    -------
    arange : ndarray
        Array of evenly spaced values.
    
        For floating point arguments, the length of the result is
        ``ceil((stop - start)/step)``.  Because of floating point overflow,
        this rule may result in the last element of `out` being greater
        than `stop`.
    
    See Also
    --------
    linspace : Evenly spaced numbers with careful handling of endpoints.
    ogrid: Arrays of evenly spaced numbers in N-dimensions.
    mgrid: Grid-shaped arrays of evenly spaced numbers in N-dimensions.
    
    Examples
    --------
    >>> np.arange(3)
    array([0, 1, 2])
    >>> np.arange(3.0)
    array([ 0.,  1.,  2.])
    >>> np.arange(3,7)
    array([3, 4, 5, 6])
    >>> np.arange(3,7,2)
    array([3, 5])

None

多维数组

创建多维数组

>>> a=np.array([np.arange(3),np.arange(3)])
>>> a
array([[0, 1, 2],
       [0, 1, 2]])
>>> a.shape#表示数组的形状
(2, 3)
>>> a.ndim#数组的维数
2

选取数组元素

数组的下标从0开始,上述数组为二维数组,可以想象成两行三列的表格。

>>> a
array([[0, 1, 2],
       [0, 1, 2]])
>>> a[1,2]#第二行第三列
2
>>> a[1,1]#第一行第二列
1

NumPy数据类型

在NumPy中,大部分数据类型名是以数字结尾的,这个数字表示其在内存中占用的位数。

类型描述
bool布尔值
inti由所在平台决定其精度的整数
int8整数,范围为-128~127
int16整数,范围为-32768~32767
int32整数,范围为-2^31 ~ 2^31-1
int64整数,范围为范围为-2^63 ~ 2^63-1
uint8无符号整数,范围为0~255
uint16无符号整数,范围为0~65535
uint32无符号整数,范围为0~2^32-1
uint64无符号整数,范围为0~2^64-1
float16半精度浮点数( 16位):其中用1位表示正负号, 5位表示指数, 10位表示尾数
float32单精度浮点数( 32位):其中用1位表示正负号, 8位表示指数, 23位表示尾数
float64或float双精度浮点数( 64位):其中用1位表示正负号, 11位表示指数, 52位表示尾数
complex64复数,分别用两个32位浮点数表示实部和虚部
complex128或complex复数,分别用两个64位浮点数表示实部和虚部
#查看完整的ndarray数据类型
print(set(np.typeDict.values()))
{<class 'numpy.int8'>, <class 'numpy.int32'>, <class 'numpy.uint64'>, <class 'numpy.int16'>, <class 'numpy.uint32'>, <class 'numpy.str_'>, <class 'numpy.datetime64'>, <class 'numpy.float32'>, <class 'numpy.bool_'>, <class 'numpy.float64'>, <class 'numpy.complex128'>, <class 'numpy.float16'>, <class 'numpy.bytes_'>, <class 'numpy.uint16'>, <class 'numpy.complex64'>, <class 'numpy.complex128'>, <class 'numpy.timedelta64'>, <class 'numpy.int32'>, <class 'numpy.uint8'>, <class 'numpy.float64'>, <class 'numpy.void'>, <class 'numpy.int64'>, <class 'numpy.uint32'>, <class 'numpy.object_'>}

自定义数据类型

dtype方法可以用来自定义数组类型:

>>> t = np.dtype([('name', np.str_, 40), ('numitems', np.int32), ('price', np.float32)])
>>> t
dtype([('name', '<U40'), ('numitems', '<i4'), ('price', '<f4')])

结构数组

结构数组为异构的数据类型,通常用于记录一行数据或一系列数据。

有两种方式构建:一是以列表的形式构建,二是以字典的形式构建。

>>> goodlist=np.dtype([('name',np.str_,50),('location',np.str_,30),('price',np.float16),('volume',np.int32)])
>>> goodlist1=np.dtype({'names':['name','location','price','volume'],'formats':['S50','S30','f','i']})
>>> goodlist
dtype([('name', '<U50'), ('location', '<U30'), ('price', '<f2'), ('volume', '<i4')])
>>> goodlist1
dtype([('name', 'S50'), ('location', 'S30'), ('price', '<f4'), ('volume', '<i4')])
>>> goods=np.array([('dgh','nantong',12,2),('dgh1','haian',13,4),goodlist])
>>> goods
array([('dgh', 'nantong', 12, 2), ('dgh1', 'haian', 13, 4),
       dtype([('name', '<U50'), ('location', '<U30'), ('price', '<f2'), ('volume', '<i4')])],
      dtype=object)

索引和切片

一维数组的切片

类似于python序列的相关索引切片。

>>> a=np.arange(9)
>>> a[3:7]
array([3, 4, 5, 6])
>>> a[:7:2]
array([0, 2, 4, 6])
>>> a[::-1]
array([8, 7, 6, 5, 4, 3, 2, 1, 0])

多维数组的切片

#多维数组的索引与切片
>>> b=np.arange(24).reshape(2,3,4)
>>> b
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]]])
>>> b.shape
(2, 3, 4)
>>> b[1,1,2]
18
>>> b[0,2,:]
array([ 8,  9, 10, 11])
>>> b[0,2]
array([ 8,  9, 10, 11])
>>> b[0,...]
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
>>> b[:,1]
array([[ 4,  5,  6,  7],
       [16, 17, 18, 19]])
>>> b[:,:,1]
array([[ 1,  5,  9],
       [13, 17, 21]])
>>> b[...,1]  #代替上面的多个冒号
array([[ 1,  5,  9],
       [13, 17, 21]])
>>> b[0,::2,-2]
array([ 2, 10])
#对于结构性数组的索引,可以直接引用其字段名来实现
#逻辑索引,即布尔型索引、条件索引
>>> b[b>15]
array([16, 17, 18, 19, 20, 21, 22, 23])
>>> b[~(b>15)]
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15])
>>> b[(b>=5)&(b<15)]
array([ 5,  6,  7,  8,  9, 10, 11, 12, 13, 14])

数组维度

展平数组

reshape改变数组的维数,使用ravel函数、flatten函数等把数组展平为一维数组。

>>> b=np.arange(24).reshape(2,3,4)
>>> b.ndim
3
>>> br=np.ravel(b)
>>> br
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])
>>> br.ndim
1
>>> brsh=b.reshape(1,1,24)
>>> brsh
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]]])
>>> brsh.ndim
3
>>> b
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]]])
>>> b.flatten()
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])
#flatten()和ravel()函数功能相同,执行flatten函数,会分配内存保存结果;ravel()函数只是返回数组的一个视图

改变维度

reshape()、resize()均可以改变数组的维度和数组的尺寸。reshape()只是返回数组的一个视图,而resize()会直接修改所操作的数组,与shape属性赋值一样。

>>> b=np.arange(24).reshape(2,3,4)
>>> bd=b.reshape(4,6)
>>> bd
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]])
>>> b
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]]])
>>> b.resize(4,6)
>>> b
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]])
>>> b.shape=(2,3,4)
>>> b
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]]])

转置数组

transpose()用于转置数组。


>>> b=np.arange(24).reshape(2,3,4)
>>> b.shape=(3,4,2)
>>> b
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]]])
>>> b.T
array([[[ 0,  8, 16],
        [ 2, 10, 18],
        [ 4, 12, 20],
        [ 6, 14, 22]],

       [[ 1,  9, 17],
        [ 3, 11, 19],
        [ 5, 13, 21],
        [ 7, 15, 23]]])
>>> np.transpose(b)
array([[[ 0,  8, 16],
        [ 2, 10, 18],
        [ 4, 12, 20],
        [ 6, 14, 22]],

       [[ 1,  9, 17],
        [ 3, 11, 19],
        [ 5, 13, 21],
        [ 7, 15, 23]]])

数组组合

NumPy数组有水平组合、垂直组合和深度组合等多种组合方式。

水平组合(hstack)

>>> a=np.arange(9).reshape(3,3)
>>> b=np.arange(12).reshape(3,4)
>>> np.hstack((a,b)) #参数只有一个,要将组合的数组放入一个元组中作为参数,组合的行数目要一致,不然会报错
array([[ 0,  1,  2,  0,  1,  2,  3],
       [ 3,  4,  5,  4,  5,  6,  7],
       [ 6,  7,  8,  8,  9, 10, 11]])
>>> np.concatenate((a,b),axis=1) #concatenate函数指定其axis参数值为1也可以实现同样的功能
array([[ 0,  1,  2,  0,  1,  2,  3],
       [ 3,  4,  5,  4,  5,  6,  7],
       [ 6,  7,  8,  8,  9, 10, 11]])

垂直组合(vstack)

>>> a=np.arange(9).reshape(3,3)
>>> b=np.arange(9).reshape(3,3)
>>> np.vstack((a,b))
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8],
       [0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
>>> np.concatenate((a,b),axis=0)#concatenate函数指定其axis参数值为0也可以实现同样的功能
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8],
       [0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])

深度组合(dstack)

深度组合即将参加组合的各数组相同位置的数据组合在一起。其要求所有数组维度属性要相同。

>>> np.dstack((a,b))#深度组合
array([[[0, 0],
        [1, 1],
        [2, 2]],

       [[3, 3],
        [4, 4],
        [5, 5]],

       [[6, 6],
        [7, 7],
        [8, 8]]])

列组合(colume_stack)

#列组合

>>> a1=np.arange(4)
>>> a2=np.arange(4)*2
>>> np.column_stack((a1,a2)) #对于一维数组,按照列的方向进行组合;对于二维数组, column_stack与hstack的效果是相同的
array([[0, 0],
       [1, 2],
       [2, 4],
       [3, 6]])

行组合(row_stack)

#行组合,对于一维数组按行方向进行组合;对于二维数组, row_stack与vstack的效果是相同的
>>> np.row_stack((a1,a2))
array([[0, 1, 2, 3],
       [0, 2, 4, 6]])

数组分拆

水平分拆(hsplit)

>>> a=np.arange(9).reshape(3,3)
>>> a
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
>>> ahs=np.hsplit(a,3)
>>> type(ahs)
<class 'list'>
>>> type(ahs[1])
<class 'numpy.ndarray'>
>>> np.split(a,3,axis=1)
[array([[0],
       [3],
       [6]]), array([[1],
       [4],
       [7]]), array([[2],
       [5],
       [8]])]

垂直分拆(vsplit)

>>> np.vsplit(a,3)
[array([[0, 1, 2]]), array([[3, 4, 5]]), array([[6, 7, 8]])]
>>> np.split(a,3,axis=0)
[array([[0, 1, 2]]), array([[3, 4, 5]]), array([[6, 7, 8]])]

深度分拆(dsplit)

>>> ads=np.arange(12)
>>> ads.shape=(2,2,3)
>>> ads
array([[[ 0,  1,  2],
        [ 3,  4,  5]],

       [[ 6,  7,  8],
        [ 9, 10, 11]]])
>>> np.dsplit(ads,3)
[array([[[0],
        [3]],

       [[6],
        [9]]]), array([[[ 1],
        [ 4]],

       [[ 7],
        [10]]]), array([[[ 2],
        [ 5]],

       [[ 8],
        [11]]])]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值