网络编程
位置:首页>> 网络编程>> Python编程>> Python的numpy库下的几个小函数的用法(小结)

Python的numpy库下的几个小函数的用法(小结)

作者:波比12  发布时间:2021-12-13 10:29:33 

标签:Python,numpy库,函数

numpy库是Python进行数据分析和矩阵运算的一个非常重要的库,可以说numpy让Python有了matlab的味道

本文主要介绍几个numpy库下的小函数。

1、mat函数

mat函数可以将目标数据的类型转换为矩阵(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

因此可以使用mat函数将一个列表a转换成相应的矩阵类型。

2、zeros

zeros函数是生成指定维数的全0数组


>>myMat=np.zeros(3)  ###生成一个一维的全0数组
>>print(myMat)
>>array([0.,0.,0.])

>>myMat1=np.zeros((3,2)) ####生成一个3*2的全0数组
>>print(myMat)
>>array([[0.,0.],
   [0.,0.]
   [0.,0.]])  

3、ones

ones函数是用于生成一个全1的数组


>>onesMat=np.ones(3)  ###1*3的全1数组
>>print(onesMat)
>>array([1.,1.,1.])

>>onesMat1=np.ones((2,3))  ###2*3的全1数组
>>print(onesMat1)
>>array([[1.,1.,1.],[1.,1.,1.]])

4.eye

eye函数用户生成指定行数的单位矩阵


>>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作用于矩阵,用作球矩阵的转置 


>>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

tolist函数用于把一个矩阵转化成为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()

getA()函数是numpy.matrix下的一个函数,用作把矩阵转换成数组,等价于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用作求矩阵的逆矩阵。逆矩阵在计算中是经常需要用到的。例如一个矩阵A,求A的逆矩阵B,即存在矩阵B是的AB=I(I为单位)


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]])

来源:https://www.cnblogs.com/itdyb/p/5773404.html

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com