In [1]:
import numpy as np from functools import partial println = partial(print,sep="\n"+"*"*50+"\n")
In [2]:
arr = np.random.randn(7) * 5 remainder, whole_part = np.modf(arr) println(arr,remainder,whole_part)
[ 3.43229669 -5.86140048 -6.59627105 -3.89258116 -0.2048788 1.86099143 -9.50394027] ************************************************** [ 0.43229669 -0.86140048 -0.59627105 -0.89258116 -0.2048788 0.86099143 -0.50394027] ************************************************** [ 3. -5. -6. -3. -0. 1. -9.]
In [3]:
#where 语句 arr = np.random.randn(4,4) result = np.where(arr>0,2,arr) println(arr,result)
[[-0.34360613 -0.00900969 0.51009993 2.42392996] [-1.10378649 0.76299971 1.7754222 -0.63318608] [ 0.73008744 0.45350325 0.24415811 1.48311092] [ 0.78689937 1.07869427 1.72881987 0.00863349]] ************************************************** [[-0.34360613 -0.00900969 2. 2. ] [-1.10378649 2. 2. -0.63318608] [ 2. 2. 2. 2. ] [ 2. 2. 2. 2. ]]
In [4]:
#布尔值数组 arr = np.random.randn(100) #第一个打印值是数组大于零的值的和,第二个打印值是大于零的个数,arr>0得出的是布尔数组 println(arr[arr>0].sum(),(arr>0).sum())
34.14799260621775 ************************************************** 48
In [5]:
println((arr>0).any(),(arr>0).all())
True ************************************************** False
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)
[[ 1 2 1 ... -10 -11 -12] [ -1 -2 -1 ... 26 27 26] [ -1 0 1 ... 4 3 4] ... [ -1 -2 -1 ... 2 3 4] [ -1 -2 -1 ... -14 -15 -16] [ 1 2 1 ... 4 5 6]]
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())
[False True True ... False True False] ************************************************** 501.0872403560831