np.zeros()函数的使用方法

2023-02-28 15:58:57
目录
函数调用方法:基础用法:进阶用法:最高级的用法:

函数调用方法:

numpy.zeros(shape, dtype=float)

各个参数意义:

    shape:创建的新数组的形状(维度)。dtype:创建新数组的数据类型。返回值:给定维度的全零数组。

    基础用法:

    import numpy as np
    
    array = np.zeros([2, 3])
    print(array)
    print(array.dtype)
    """
    result:
    [[0. 0. 0.]
     [0. 0. 0.]]
    float64
    """

    可以看到我们成功创建了一个2行3列的全零二维数组。并且创建的数组中的数据类型是np.float64类型。

    进阶用法:

    import numpy as np
    
    array = np.zeros([2, 3], dtype=np.int32)
    print(array)
    print(array.dtype)
    """
    result:
    [[0 0 0]
     [0 0 0]]
    int32
    """

    可以看到,这里我们同样成功创建了一个2行3列的全零二维数组。并且我们指定了其数据类型为np.int32。

    最高级的用法:

    import numpy as np
    
    # Create rain data
    n_drops = 10
    
    rain_drops = np.zeros(n_drops, dtype=[('position', float, (2,)),
                                          ('size', float),
                                          ('growth', float),
                                          ('color', float, (4,))])
    
    # Initialize the raindrops in random positions and with
    # random growth rates.
    rain_drops['position'] = np.random.uniform(0, 1, (n_drops, 2))
    rain_drops['growth'] = np.random.uniform(50, 200, n_drops)
    
    print(rain_drops)
    """
    result:
    [([0.70284885, 0.03590322], 0., 176.4511602 , [0., 0., 0., 0.])
     ([0.60838294, 0.49185854], 0.,  60.51037667, [0., 0., 0., 0.])
     ([0.86525398, 0.65607663], 0., 168.00795695, [0., 0., 0., 0.])
     ([0.25812877, 0.14484747], 0.,  80.17753717, [0., 0., 0., 0.])
     ([0.66021716, 0.90449213], 0., 121.94125106, [0., 0., 0., 0.])
     ([0.88306332, 0.51074725], 0.,  92.4377108 , [0., 0., 0., 0.])
     ([0.68916433, 0.89543162], 0.,  90.77596431, [0., 0., 0., 0.])
     ([0.7105655 , 0.68628326], 0., 144.88783652, [0., 0., 0., 0.])
     ([0.6894679 , 0.90203559], 0., 167.40736266, [0., 0., 0., 0.])
     ([0.92558218, 0.34232054], 0.,  93.48654986, [0., 0., 0., 0.])]
    """

    到此这篇关于np.zeros()函数的使用方法的文章就介绍到这了,更多相关np.zeros()使用内容请搜索易采站长站以前的文章或继续浏览下面的相关文章希望大家以后多多支持易采站长站!