在Python中,使用NumPy库可以方便地创建不同类型的数组。以下是一些常见的创建NumPy数组的方法:
numpy.array()
函数创建一维数组:import numpy as np
arr1d = np.array([1, 2, 3, 4, 5])
print(arr1d)
numpy.arange()
函数创建等差数列数组:import numpy as np
arr_arange = np.arange(start=1, stop=6, step=1)
print(arr_arange)
numpy.linspace()
函数创建等距数列数组:import numpy as np
arr_linspace = np.linspace(start=1, stop=5, num=5)
print(arr_linspace)
numpy.zeros()
函数创建全零数组:import numpy as np
arr_zeros = np.zeros(shape=(3, 3))
print(arr_zeros)
numpy.ones()
函数创建全1数组:import numpy as np
arr_ones = np.ones(shape=(3, 3))
print(arr_ones)
numpy.eye()
函数创建单位矩阵:import numpy as np
arr_eye = np.eye(3)
print(arr_eye)
numpy.random.rand()
函数创建随机数数组:import numpy as np
arr_rand = np.random.rand(3, 3)
print(arr_rand)
numpy.random.randint()
函数创建随机整数数组:import numpy as np
arr_randint = np.random.randint(low=1, high=10, size=(3, 3))
print(arr_randint)
这些方法可以根据需要创建不同类型的NumPy数组。