python Numpy 函数整理

本文介绍了Python Numpy库中用于创建数组的几个主要函数,包括array()、empty()、eye()、identity()、ones()、zeros()和tile()。详细讲解了它们的参数、返回值及其在创建不同类型的矩阵时的应用。
摘要由CSDN通过智能技术生成

一、数组创建

1、创建二维数组 array()、数组行数 shape[0]、数组列数 shape[1]
>>> a = np.array([[1,2], [3, 4], [5,6], [7,8]])
>>> a
		 
array([[1, 2],
       [3, 4],
       [5, 6],
       [7, 8]])		 
>>> a.shape[0]
		 
4
>>> a.shape[1]
		 
2
>>> a.shape
		 
(4, 2)
2、numpy.empty(shape, dtype=float, order=’C’)
参数:
  • shape:int或int类型元组,表示矩阵形状
  • dtype:输出的数据类型
  • order:‘C’ 或者 ‘F’,表示数组在内存的存放次序是以行(C)为主还是以列(F)为主
返回值:

生成随机矩阵

>>> import numpy as np
>>> np.empty([3,3])
array([[8.82769181e+025, 7.36662981e+228, 7.54894003e+252],
       [2.95479883e+137, 1.42800637e+248, 2.64686750e+180],
       [2.25567100e+137, 9.16208010e-072, 0.00000000e+000]])
>>> np.empty([2,2], dtype = int)
array([[538970739, 757932064],
       [757935405, 757935405]])
3、numpy.eye(N, M=None, k=0, dtype=float)
参数:
  • N:行数
  • M:列数,省略代表M=N
  • k:对角线位置, = 0 代表主对角线, +1就向右上方偏移1, -1 就向左下角偏移1
  • dtype:输出的数据类型,默认为float类型
返回值:

对角矩阵(主对角线上元素都为1,其他元素都为0)——对角线向右上方偏移k(k>0向右上方偏移,k<0向左下方偏移)

>>> b = np.eye(2, 3, dtype = int)
		 
>>> b
		 
array([[1, 0, 0],
       [0, 1, 0]])
>>> c = np.eye(3, k = 1 ,dtype = int)
		 
>>> c
		 
array([[0, 1, 0],
       [0, 0, 1],
       [0, 0, 0]])
4、numpy.identity(n, dtype=None)
参数:
  • n:行数(也是列数)
  • dtype:输出的数据类型
返回值:

n*n对角矩阵(主对角线上元素都为1,其他元素都为0)

>>> np.identity(3)
		 
array([[1., 0., 0.],
       [0., 1., 0.],
       [0., 0., 1.]])

5、numpy.ones(shape, dtype=None, order=’C’)
参数:
  • shape:int或int类型序列,表示矩阵形状
  • dtype:输出的数据类型
  • order:‘C’ 或者 ‘F’,表示数组在内存的存放次序是以行(C)为主还是以列(F)为主
返回值:

给定要求下的单位矩阵

>>> a = np.ones((3,3), dtype = int)
		 
>>> a
		 
array([[1, 1, 1],
       [1, 1, 1],
       [1, 1, 1]])
6、numpy.zeros(shape, dtype=float, order=’C’)
参数:
  • shape:int或int类型序列,表示矩阵形状
  • dtype:输出的数据类型
  • order:‘C’ 或者 ‘F’,表示数组在内存的存放次序是以行(C)为主还是以列(F)为主
返回值:

给定要求下的0矩阵

>>> a = np.zeros((3,3), dtype = int)
		 
>>> a
		 
array([[0, 0, 0],
       [0, 0, 0],
       [0, 0, 0]])
6、numpy.tile(A, (y, x))
参数:
  • A:要操作的数组
  • (y, x):把数组A沿y轴复制y倍,再沿x轴复制x倍
返回值:

给定要求下的矩阵

>>> a = np.array([0,1,2])
>>> np.tile(a, (2, 3))
		 
array([[0, 1, 2, 0, 1, 2, 0, 1, 2],
       [0, 1, 2, 0, 1, 2, 0, 1, 2]])


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值