• Numpy入门(二):Numpy数组索引切片和运算


    在Numpy中建立了数组或者矩阵后,需要访问数组里的成员,改变元素,并对数组进行切分和计算。

    索引和切片

    Numpy数组的访问模式和python中的list相似,在多维的数组中使用, 进行区分:

    在python的list 下:

    a = [1,2,4]
    print a[2:]
    

    打印出:

    [4]
    

    这是一个数组,在Numpy的多维数组中也采用相同的模式进行数组的访问:

    import numpy as np
    
    a = np.arange(1,37)
    a = a.reshape(6,6)
    print a
    

    打印:

    [[ 1  2  3  4  5  6]
     [ 7  8  9 10 11 12]
     [13 14 15 16 17 18]
     [19 20 21 22 23 24]
     [25 26 27 28 29 30]
     [31 32 33 34 35 36]]
    
    a[1,1] = 8
    print a
    

    打印:

    [[ 1  2  3  4  5  6]
     [ 7  8  9 10 11 12]
     [13 14 15 16 17 18]
     [19 20 21 22 23 24]
     [25 26 27 28 29 30]
     [31 32 33 34 35 36]]
    
    print a[1:4,3:]
    

    打印:

    [[10 11 12]
     [16 17 18]
     [22 23 24]]
    

    在二维数组中较为简单,, 前面是横坐标,, 后面是纵坐标,可以用这种方式推广到多维的数组。

    牢记这一点,再看看下面的布尔索引就简单多了:

    >>> arr3 = (np.arange(36)).reshape(6,6)
    >>> arr3
    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],
           [24, 25, 26, 27, 28, 29],
           [30, 31, 32, 33, 34, 35]])
    >>> x = np.array([0, 1, 2, 1, 4, 5])
    >>> arr3[x == 1]
    array([[ 6,  7,  8,  9, 10, 11],
           [18, 19, 20, 21, 22, 23]])
    >>> arr3[:,x == 1]
    array([[ 1,  3],
           [ 7,  9],
           [13, 15],
           [19, 21],
           [25, 27],
           [31, 33]])
    >>>
    

    矩阵的运算

    Numpy提供的较多的矩阵运算,可以查看相应的文档,这里介绍几种常见的运算方式来说明如何使用运算。

    numpy.sum 对某一维进行求和运算:

    import numpy as np
    
    a = np.arange(1,7)
    a = a.reshape(2,3)
    print a
    
    print np.sum(a)
    # 21
    
    #[[1 2 3]
     #[4 5 6]]
    	
    print np.sum(a,0)
    #[5 7 9]
    
    print np.sum(a,1)
    #[ 6 15]
    

    同样的运算还用numpy.argmaxnumpy.mean 等。

    数组中的运算是对每个元素进行的运算,如:

    import numpy as np
    
    a = np.arange(1,7)
    a = a.reshape(2,3)
    print 2*a
    #[[ 2  4  6]
    #[ 8 10 12]]
    

    数组的点乘操作:

    >>> a = [[1, 0], [0, 1]]
    >>> b = [[4, 1], [2, 2]]
    >>> np.dot(a, b)
    array([[4, 1],
           [2, 2]])
    

    Numpy提供了大量的运算函数,在机器学习中也经常用到,对Numpy的熟悉,以后学起机器学习会轻松很多。

    更多教程:阿猫学编程

  • 相关阅读:
    Optional int parameter 'resourceState' is present but cannot be translated into a null value
    创建第一个react项目
    后台接收参数报错 Required String parameter 'id' is not present
    sql查询条件参数为空
    斐波那契数列
    Map获取key值
    Java8之集合排序
    Android学习笔记(4)----Rendering Problems(The graphics preview in the layout editor may not be accurate)
    LeetCode赛题395----Longest Substring with At Least K Repeating Characters
    LeetCode赛题394----Decode String
  • 原文地址:https://www.cnblogs.com/bugingcode/p/8303836.html
Copyright © 2020-2023  润新知