numpy 学习2

In [1]: import numpy as np

In [2]: a = np.arange(9)

In [3]: a[3:7]
Out[3]: array([3, 4, 5, 6])

In [4]: a[:7:2]
Out[4]: array([0, 2, 4, 6])

In [5]: a[::-1]
Out[5]: array([8, 7, 6, 5, 4, 3, 2, 1, 0])

Slicing of one-dimensional NumPy arrays works just like the slicing of standard Python lists.

We can manipulate arrary shapes using the following functions:
    Ravel:We can accomplish this with the ravel() function as follows:
        In [22]: import numpy as np

        In [23]: b = np.arange(24).reshape(2,3,4)

        In [24]: b
        Out[24]: 
        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:The appropriately named function,flatten(),dose the same as travel().However,flatten() always allocates new memory,where as ravel might give back a view of the array.This means that we can directly manipulate the array as follows:
        
    In [25]: b.flatten()
    Out[25]: 
    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])

    Setting the shape with a tuple:Besides the reshape() function,we can also define the shape straightaway with a tuple,which is exhibited as follows:
    In [26]: b.shape = (6,4)

    In [27]: b
    Out[27]: 
    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]])

    As you can understand,the preceding code alters the array immediately.Now,we have a 6*4 array.

    Transpose:In linear algebra,it is common to transpose matrices.Transposing is a way to transform data.For a two-dimensional table,transposing means that rows become columns and cloumns become rows.We can do this too by using the following code:
    In [33]: a = b.transpose()

    In [34]: a
    Out[34]: 
    array([[ 0,  4,  8, 12, 16, 20],
           [ 1,  5,  9, 13, 17, 21],
           [ 2,  6, 10, 14, 18, 22],
           [ 3,  7, 11, 15, 19, 23]])

    Resize:The resize() method works just like the reshape() method,but changes the array it works on:
        In [37]: b.resize((2,12))

        In [38]: b
        Out[38]: 
        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]])


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值