• 技术文章 >Python技术 >Python基础教程

    python中如何基于numpy创建矩阵

    宋雪维宋雪维2021-01-29 09:19:52原创13133

    python的功能强大依赖于各种库发挥的作用,例如numpy库就提供了矩阵运算的功能,如果我们想要进行矩阵运算,首先要导入numpy的包,创建矩阵。本文介绍python中基于numpy创建矩阵的三种方法:1、手动创建;2、利用numpy数组创建;3、使用numpy.matix()函数创建矩阵。

    一、导入numpy

    1

    2

    >>>from numpy import *;#导入numpy的库函数

    >>>import numpy as np; #这个方式使用numpy的函数时,需要以np.开头。

    二、python基于numpy创建矩阵方法

    1、手动创建

    1

    a=np.mat('1 2 3;4 5 6;7 8 9') # 中间打逗号也可以 b=np.mat('1,2,3;4,5,6;7,8,9')

    2、利用numpy数组创建

    1

    2

    c=np.mat(np.arange(9)) #一维的矩阵

    c=np.mat(np.arange(9).reshape(3,3))

    3、使用numpy.matix()函数创建矩阵

    1

    2

    3

    4

    5

    6

    7

    import numpy as np

      

    # create 2x2 matrix

    a = np.matrix([[1, 2], [3, 4]])  # using array of array

    print('2x2 matrix is:\n', a)

    # using shape attribute to get the tuple describing matrix shape

    print('The dimension of the matrix is :', a.shape)

    以上就是python中基于numpy创建矩阵的三种方法,希望能帮助到你进行创建矩阵哦~

    专题推荐:python基础
    上一篇:python如何使用numpy中的size()函数? 下一篇:python实现矩阵乘法运算的几种方法

    相关文章推荐

    • python中如何使用pandas实现行数据添加• python中写入文件的出错解决• python中len是什么意思?• python如何使用numpy中的size()函数?

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网