In [1]:
import numpy as np
from functools import partial
println = partial(print,sep="
"+"*"*50+"
")
In [2]:
arr = np.random.randn(7) * 5
remainder, whole_part = np.modf(arr)
println(arr,remainder,whole_part)
In [3]:
#where 语句
arr = np.random.randn(4,4)
result = np.where(arr>0,2,arr)
println(arr,result)
In [4]:
#布尔值数组
arr = np.random.randn(100)
#第一个打印值是数组大于零的值的和,第二个打印值是大于零的个数,arr>0得出的是布尔数组
println(arr[arr>0].sum(),(arr>0).sum())
In [5]:
println((arr>0).any(),(arr>0).all())
In [6]:
#模拟随机漫步
nwalks = 5000 #样本数
nsteps = 1000
draws = np.random.randint(0,2,size=(nwalks,nsteps)) #0或1
steps = np.where(draws>0,1,-1) #1或-1
walks = steps.cumsum(1) #步数相加
print(walks)
In [7]:
#想算出走到30或-30的时间,先把未走到的样本剔除
index_hit30 = (np.abs(walks)>=30).any(1)
hit30 = walks[index_hit30]
#第一次走到30或-30的时间
hit30_time = (np.abs(hit30)>=30).argmax(1)
println(index_hit30,hit30_time.mean())
In [2]:
#最值及排序
data = np.sin(np.arange(20).reshape(4,-1))
max_index = np.argmax(data,axis=0)
println(data,max_index,data[max_index,range(data.shape[1])])
In [4]:
sort_index = np.argsort(data[0])
sort_index
Out[4]:
In [5]:
data[0,sort_index]
Out[5]: