第4章:Numpy基础:数组和向量化计算
import random
import numpy as np
import matplotlib.pyplot as plt
rng=np.random.default_rng(seed=12345)
#创建ndarray,列表转换
data1=[1,2,3,4,5,6]
arr1=np.array(data1)
print(arr1)
#嵌套序列
data2=[[1,2,3,4],[5,6,7,8]]
arr2=np.array(data2)
print(arr2)
print(arr2.ndim)
print(arr2.shape)
#全0数组
print(np.zeros((3,3,3)))
#arrange类似于range,返回的是ndarry
print(np.arange((10)))
#数组运算
#切片
arr3=np.arange(9).reshape(3,3)
print(arr3[:3,1:])
#花式索引,转置
arr4=np.arange(20).reshape(5,4)
print(arr4[[1,3,2,0],[2,3,3,1]])
print(arr4[[1,3,2,0]][:,[2,3,3]])
print(arr4.T)
print(arr4.swapaxes(0,1))
#伪随机数
#标准正态分布
arr5=np.random.standard_normal(size=(4,4))
print(arr5)
#通用函数,试用了几个
rng=np.random.default_rng(seed=12345)
x=rng.standard_normal(8)
y=rng.standard_normal(8)
print(x)
print(np.maximum(x,y))
print(np.subtract(x,y))
print(np.add(x,1))
print(np.zeros_like(x))
print(np.isinf(x))
#面向数组编程
points=np.arange(-5,5,0.01)
xs,ys=np.meshgrid(points,points)
z=np.sqrt(xs**2+ys**2)
#print(z)
plt.imshow(z, cmap=plt.cm.gray,extent=[-5,5,-5,5])
plt.colorbar()
plt.title({"Image plot"})
plt.close("all")
#条件逻辑表述为数组运算
xarr=np.array([1.1,1.2,1.3,1.4,1.5])
yarr=np.array([2.1,2.2,2.3,2.4,2.5])
cond=np.array([True,False,True,True,False])
result=np.where(cond,xarr,yarr)
#print(result)
#where的用法
arr6=rng.standard_normal((4,4))
print(arr6>0)
print(np.where(arr6>0,2,-2))
print(np.where(arr6>0,2,arr6))#仅正值设为2
#数学和统计方法
arr7=rng.standard_normal((5,4))
print(np.mean(arr7))
print(arr7.mean(axis=1))#每行的均值
print(arr7.sum())
print(arr7.sum(axis=0))#每列的和
print(arr7.cumsum(axis=0))#每行依次累积和
print(arr7.cumsum(axis=1))#每列依次累积和
print(arr7.var())#方差
print(arr7.cumsum(axis=0))#从0开始元素累积和
#布尔型数组
arr8=rng.standard_normal(100)
print((arr8>0).sum())
bools=np.array([False,False,True,False])
print(bools.any())#是否存在T
print(bools.all())#是否全是T
#排序
arr9=rng.standard_normal(6)
print(arr9)
arr9.sort()
print(arr9)
arr10=rng.standard_normal((5,3))
print(arr10)
arr10.sort(axis=0)#按每一列排序
print(arr10)
arr10.sort(axis=1)#按每一行排序
print(arr10)
#唯一化和其他集合逻辑
names=np.array(["Bob","Will","Joe","Bob","Will","Joe","Bob"])
print(np.unique(names))#找出唯一值
values=np.array([6,0,0,3,2,5,6])
print(np.isin(values,[2,3,6]))
#线性代数
A=np.array([[1.,2.,3.],[4.,5.,6.]])
B=np.array([[6.,23.],[-1,7],[8,9]])
print(A.dot(B))#矩阵点积运算
#示例:随机漫步
position=0
walk=[position]
nsteps=1000
for _ in range(nsteps):
step=1 if random.randint(0,1) else -1
position+=step
walk.append(position)
plt.plot(walk[:100])