Usage of several small functions under numpy library of Python Summary of of

  • 2021-07-13 06:03:02
  • OfStack

numpy library is a very important library for Python to analyze data and calculate matrix. It can be said that numpy makes Python have the taste of matlab

This paper mainly introduces several small functions under numpy library.

1. mat function

The mat function converts the type of the target data to a matrix (matrix)


import numpy as np

>>a=[[1,2,3,],

   [3,2,1]]

>>type(a)

>>list

 
>>myMat=np.mat(a)

>>myMat

>>matrix([[1,2,3],[3,2,1]])

 

>>type(myMat)

>>numpy.matrixlib.defmatrix.martix 

So you can use the mat function to convert a list a to the corresponding matrix type.

2. zeros

The zeros function generates an all-zeros array of the specified dimension


>>myMat=np.zeros(3)  ### Generate 1 A 1 Completeness of dimension 0 Array 
>>print(myMat)
>>array([0.,0.,0.])


>>myMat1=np.zeros((3,2)) #### Generate 1 A 3*2 Complete of 0 Array 
>>print(myMat)
>>array([[0.,0.],
    [0.,0.]
    [0.,0.]])  

3. ones

The ones function is used to generate an array of all ones


>>onesMat=np.ones(3)  ###1*3 Complete of 1 Array 
>>print(onesMat)
>>array([1.,1.,1.])



>>onesMat1=np.ones((2,3))  ###2*3 Complete of 1 Array 
>>print(onesMat1)
>>array([[1.,1.,1.],[1.,1.,1.]])

4.eye

The eye function user generates a unity matrix for the specified number of rows


>>eyeMat=np.eye(4) 
>>print(eyeMat)
>>array([[1.,0.,0.,0.],
    [0.,1.,0.,0.],
    [0.,0.,1.,0.,],
    [0.,0.,0.,1.]])

5. T

T acts on the matrix and is used as a transpose of the spherical matrix


>>myMat=np.mat([[1,2,3],[4,5,6]])
>>print(myMat)
>>matrix([[1.,2.,3.]
     [4.,5.,6.]])


>>print(myMat.T)
>>matrix([[1,4] , 
     [2,5],
     [3,6]])   

6. tolist

The tolist function is used to convert a matrix into an list list


>>x=np.mat([[1,2,3],[4,5,6]])

>>print(x)

>>matrix([[1,2,3],[4,,5,6]])

>>type(x)

>>matrix

 

 

>>x.tolist()

>>[[1,2,3],[4,5,6]] 

7.getA()

The getA () function is a function under numpy. matrix, which is used to convert a matrix into an array and is equivalent to np. asarray (self).


>>> x = np.matrix(np.arange(12).reshape((3,4))); x

matrix([[ 0, 1, 2, 3],

    [ 4, 5, 6, 7],

    [ 8, 9, 10, 11]])

>>> x.getA()

array([[ 0, 1, 2, 3],

    [ 4, 5, 6, 7],

    [ 8, 9, 10, 11]]) 

8. .I

. I is used to find the inverse matrix of the matrix. Inverse matrix is often used in calculation. For example, for a matrix A, find the inverse matrix B of A, that is, AB = I where the existence matrix B is (I is the unit)


In [3]: a=mat([[1,2,3],[4,5,6]])

 

In [4]: a

Out[4]:

matrix([[1, 2, 3],

    [4, 5, 6]])

 

 

In [5]: a.I

Out[5]:

matrix([[-0.94444444, 0.44444444],

    [-0.11111111, 0.11111111],

    [ 0.72222222, -0.22222222]])

In [6]: s=a.I 

In [8]: a*s

Out[8]:

matrix([[ 1.00000000e+00,  3.33066907e-16],

    [ 0.00000000e+00,  1.00000000e+00]]) 


Related articles: