NumPy(Numerical Python) 是科学计算基础库,提供大量科学计算相关功能,比如数据统计,随机数生成等。其提供最核心类型为多维数组类型(ndarray),支持大量的维度数组与矩阵运算,Numpy 支持向量处理ndarray 对象,提高程序运算速度。
# 安装numpy
pip install numpy
1 array创建数组
语法:
numpy.array(object, dtype = None, copy = True, order = None, subok = False, ndmin = 0)
| 参数 | 描述 |
| object | 数组或嵌套的数列 |
| dtype | 数组元素的数据类型,可选 |
| copy | 对象是否需要复制,可选 |
| order | 创建数组的样式,C 为行方向,F 为列方向,A 为任意方向(默 认) |
| subok | 默认返回一个与基类类型一致的数组 |
| ndmin | 指定生成数组的最小维度 |
import numpy as np# 创建一维数组
a=np.array([1,2,3,4,5])
print("a:",a)# 创建二维数组
b=np.array([[1,2,3],[4,5,6],[7,8,9]])
print("b:\n",b)# ndmin参数,三维
c=np.array([1,2,3,4,5],ndmin=3)
print("c:\n",c)# dtype参数
d=np.array([1,2,3,4,5],dtype=float)
print("d:\n",d)
执行结果:
a: [1 2 3 4 5]
b:[[1 2 3][4 5 6][7 8 9]]
c:[[[1 2 3 4 5]]]
d:[1. 2. 3. 4. 5.]
2 arange创建数组
3 随机数创建
import numpy as np# 返回[0.0, 1.0)范围的随机数
a=np.random.random(size=4)
b=np.random.random(size=(2,3))
print(a)
print(b)# 返回[low,high)范围的随机数
c=np.random.randint(5,10,size=4)
d=np.random.randint(5,10,size=(2,3))
print(c)
print(d)# randn函数返回一个或一组样本,具有标准正态分布(期望为0,方差为1)
e=np.random.randn(2,4)
print(e)# 正太分布(高斯分布),loc:期望,scale:方差,size 形状
f=np.random.normal(loc=3,scale=4,size=(2,3))
print(f)
执行结果:
[0.35107183 0.56081434 0.61495015 0.63428097][[0.2684299 0.47761707 0.19357864][0.29151876 0.37637427 0.78823579]][7 7 6 7]
[[7 9 7][5 8 5]][[ 0.60840793 -1.05643424 -1.70151912 0.57745096][-1.33469862 -1.81341201 -0.93015908 -0.79829661]][[ 3.12894402 4.13076526 -2.34580941][ 3.44540538 0.29992472 1.80381665]]