网络编程
位置:首页>> 网络编程>> Python编程>> np.zeros()函数的使用方法

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

作者:勤奋的大熊猫  发布时间:2023-11-10 06:33:36 

标签:np.zeros,使用

函数调用方法:

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

来源:https://blog.csdn.net/u011699626/article/details/122193581

0
投稿

猜你喜欢

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