Data analysis using python Notes a: numpy function

function

  1. numpy.cumsum ()
    numpy.cumsum (A, axis = None, DTYPE = None, OUT = None)
    Function: is returned to and accumulated on a given axis
    parameters: A- array; axis - axis; dtype- data type
    instance :
    one-dimensional
>>>import numpy as np
>>> a=[1,2,3,4,5,6,7]
>>> np.cumsum(a)
array([  1,   3,   6,  10,  15,  21,  28])

Multidimensional

>>>import numpy as np
>>> c=[[1,2,3],[4,5,6],[7,8,9]]
>>> np.cumsum(c,axis=0) 
#axis=0,代表以行方式扫描,第一次扫描第一行,第二次扫描第二行,以此类推。
#第一行扫描时,没有前几行可累加,所以数值不变。扫描到第二行,累加前几行,以此类推。
array([[ 1,  2,  3],
       [ 5,  7,  9],
       [12, 15, 18]])

#也可以这样表示,结果与上面的相同
>>>c.cumsum(0)
  1. np.argmax ()
    Function: Returns the index of the axis corresponding to the maximum value
    Example:
    one-dimensional array
import numpy as np
a = np.array([3, 1, 2, 4, 6, 1])
b=np.argmax(a)#取出a中元素最大值所对应的索引,此时最大值位6,其对应的位置索引值为4,(索引值默认从0开始)
print(b)#4

Multidimensional Arrays

a = np.array([[1, 5, 5, 2],
              [9, 6, 2, 8],
              [3, 7, 9, 1]])
b=np.argmax(a, axis=0)#对二维矩阵来讲a[0][1]会有两个索引方向,第一个方向为a[0],默认按列方向搜索最大值
#a的第一列为1,9,3,最大值为9,所在位置为1,
#a的第一列为5,6,7,最大值为7,所在位置为2,
#此此类推,因为a有4列,所以得到的b为1行4列,
print(b)#[1 2 2 1]
  1. numpy.mean ()
    numpy.mean (A, axis, DTYPE, OUT, keepdims)
    Function: Averaging
    regular operating parameters for the axis, to m * n matrix Example:
  • axis is not the set value of m * n averaging number, returns a real number
  • axis = 0: compressed row, each column averaging Returns 1 * n matrix
  • axis = 1: compress columns, each row averaging, m * 1 matrix returned

Example:
the operation of the array

>>> a = np.array([[1, 2], [3, 4]])
>>> np.mean(a)
2.5
>>> np.mean(a, axis=0) # axis=0,计算每一列的均值
array([ 2.,  3.])
>>> np.mean(a, axis=1) # 计算每一行的均值 
array([ 1.5,  3.5])

Matrix operations

>>> import numpy as np
>>> num1 = np.array([[1,2,3],[2,3,4],[3,4,5],[4,5,6]])
>>> num1
array([[1, 2, 3],
       [2, 3, 4],
       [3, 4, 5],
       [4, 5, 6]])
>>> num2 = np.mat(num1)
>>> num2
matrix([[1, 2, 3],
        [2, 3, 4],
        [3, 4, 5],
        [4, 5, 6]])
>>> np.mean(num2) # 对所有元素求均值
3.5
>>> np.mean(num2,0) # 压缩行,对各列求均值
matrix([[ 2.5,  3.5,  4.5]])
>>> np.mean(num2,1) # 压缩列,对各行求均值
matrix([[ 2.],
        [ 3.],
        [ 4.],
        [ 5.]])
>>> 
  1. Two-dimensional matrix transpose function
    link: transpose function uses the method of numpy
Released three original articles · won praise 2 · Views 454

Guess you like

Origin blog.csdn.net/lllalaaaa/article/details/104070431