numpy中有关各种array的创建

numpy中有关各种array的创建,第1张

numpy中有关各种array的创建 有关array的创建 创建规则矩阵 Array
np.array(arr)
  • Example:

    import numpy as np
    cars = np.array([5,10,12,6])
    print(cars)
    

    Run:

    [5,10,12,6]

Linspace
np.linspace(start,end,num,endpoint)
  • 创造间隔一样的点

  • start 起点

  • end 终点

  • num 需要几个点

  • endpoint 是否算最后一个节点

  • Example:

    x = np.linspace(-1,1,5)
    y = np.linspace(-1,1,5,endpoint=False)
    

    Run:

    [-1. -0.5 0. 0.5 1. ]

    [-1. -0.6 -0.2 0.2 0.6]

创建特殊规则矩阵 Identify
np.identify(n)
  • 用于创建方型矩阵

  • Example:

    arr = np.identify(4)
    

    Run:

    [[1. 0. 0. 0.]
    [0. 1. 0. 0.]
    [0. 0. 1. 0.]
    [0. 0. 0. 1.]]

Eye
np.eye(row,column,k)
  • 可以创建矩形矩阵

  • k 偏移量,为1的对角线的位置偏离度,0居中,1向上偏离1,2偏离2,以此类推,-1向下偏离。值绝对值过大就偏离出去了,整个矩阵就全是0了

  • Example:

    arr1 = np.eye(4,3)
    

    Run:

    [[1. 0. 0.]
    [0. 1. 0.]
    [0. 0. 1.]
    [0. 0. 0.]]

Logspace
np.logspace(start,end,num)
  • 创建10start ~10end之间的num个数

  • Example:

    arr = np.logspace(3,4,5)
    

    Run:

    [ 1000. 1778.27941004 3162.27766017 5623.4132519 10000.]

创建统一矩阵 Zeros
np.zeros([row,column])
  • 常用于初始化一个全为0的数组
ones
np.ones([row,column])
  • 常用于初始化一个全为1的数组
Full
np.full([row,culumn],num)
  • 用于创建指定num的数组

  • Example:

    nines = np.full([2,3],9)
    

    Run:

    [[9 9 9]
    [9 9 9]]

Ones_like
np.ones_like(arr)
  • 用于创建已经创建好的零数组

  • Example:

    data = np.array([
    [1,2,3],
    [4,5,6]
    ], dtype=np.int)
    
    ones = np.ones(data.shape, dtype=data.dtype)
    ones_like = np.ones_like(data)
    

    Run:

    ones: (2, 3) int32
    ones_like: (2, 3) int32
    ones_like value:
    [[1 1 1]
    [1 1 1]]

  • 类似的还有zeros_like,full_like

Empty
np.empty([row,column])
  • 快速创建一个数组,之后再对其进行填充

  • Example:

    import random
    
    empty = np.empty([2,3])
    print("empty before:n", empty)
    data = np.arange(6).reshape([2, 3])
    for i in range(data.shape[0]):
        for j in range(data.shape[1]):
            empty[i, j] = data[i, j] * random.random()
    print("empty after:n", empty)
    

    Run:

    empty before:
    [[9.30473091e-308 8.71186223e-308 8.71186221e-308]
    [1.53249677e-317 0.00000000e+000 8.94905028e-299]]
    empty after:
    [[0. 0.7818448 1.69389831]
    [0.74340454 1.7203021 4.40158137]]

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5491103.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-12
下一篇 2022-12-12

发表评论

登录后才能评论

评论列表(0条)

保存