在Python中,你可以使用NumPy库来生成数组。以下是一些常用的NumPy函数:
1.numpy.zeros(shape, dtype=float, order='C')
: 创建指定形状的全零数组。
import numpy as np
zeros_array = np.zeros((3, 4)) # 3x4的全零数组
print(zeros_array)
输出结果:
[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]
2.numpy.ones(shape, dtype=None, order='C')
: 创建指定形状的全一数组。
import numpy as np
ones_array = np.ones((2, 3)) # 2x3的全一数组
print(ones_array)
输出结果:
[[1. 1. 1.]
[1. 1. 1.]]
3.numpy.arange([start, ]stop, [step, ]dtype=None)
: 根据指定的范围和步长创建一个数组(一维)。
|
import numpy as np
range_array = np.arange(0, 10, 2) # 步长为2的数组:[0, 2, 4, 6, 8]
print(range_array)
输出结果:
[0 2 4 6 8]
4.numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0)
: 在指定的范围内生成指定数量的均匀间隔的数组。
import numpy as np
linspace_array = np.linspace(0, 1, 5) # 在0到1之间生成5个均匀间隔的值
print(linspace_array)
输出结果:
[0. 0.25 0.5 0.75 1. ]
5.numpy.random.rand(d0, d1, ..., dn)
: 生成指定形状的在 [0, 1) 之间均匀分布的随机数组。
import numpy as np
random_array = np.random.rand(2, 3) # 2x3的随机数组
print(random_array)
输出结果:
[[0.38498201 0.12279646 0.5405502 ]
[0.85754413 0.48989254 0.73803307]]
6.numpy.random.randn(d0, d1, ..., dn)
: 生成指定形状的服从标准正态分布的随机数组。
import numpy as np
standard_normal_array = np.random.randn(3, 3) # 3x3的标准正态分布的随机数组
print(standard_normal_array)
输出结果:
[[-0.2285309 1.6453652 0.04606316]
[-0.58597483 -2.72652979 1.46935731]
[-0.40929189 3.09180215 0.27977861]]
7.np.random.uniform(low,high,size):
用于生成服从均匀分布的随机数。
import numpy as np
low = 1 # 最小值
high = 10 # 最大值
size = (3, 3)
positive_array = np.random.uniform(low, high, size)
print(positive_array)
输出结果:
[[2.79252572 4.90595938 4.24445763]
[7.20844023 3.97952466 7.06187543]
[9.14082072 6.9662539 9.29921067]]
8.np.array(object,dtype=None,copy=True ,order='C',subok=Ture,ndmin=None):接受一些可转换为数组的输入,并返回一个新的 NumPy 数组。
参数说明:
- object: 输入的数组或类数组对象。可以是列表、元组、其他数组等。
- dtype: 数组的数据类型。如果未指定,NumPy 会根据输入数据自动推断。
- copy: 默认为 True,表示复制输入数组。如果为 False,将尽量避免复制,当输入数据是 NumPy 数组时,会共享相同的数据。
- order: 数组的存储顺序,可以是 'C'(按行存储)或 'F'(按列存储)。
- subok: 如果为 True,子类将被传递;如果为 False,则返回基类数组(默认为 True)。
- ndmin: 指定返回数组的最小维数。
import numpy as np
# 创建二维数组
arr_2d = np.array([[1, 2, 3], [4, 5, 6]])
# 打印数组及其属性
print("Array:\n", arr_2d)
print("Shape:", arr_2d.shape)
print("Data Type:", arr_2d.dtype)
输出结果:
Array:
[[1 2 3]
[4 5 6]]
Shape: (2, 3)
Data Type: int32