我正在尝试创建一个循环,该循环将根据numpy创建的统一随机数为CDO的不同沟槽选择优惠券。
如果rand <0.25
A得到兰特* $ 5
如果兰特 如果rand <0.75
A获得0.25 * $ 5
B得到0.25 * $ 5
C得到(rand-0.5)* $ 5 如果rand <1
A获得0.25 * $ 5
B得到0.25 * $ 5
C得到0.25 * $ 5
D得到(rand-0.75)* $ 5 我为20个债券投资组合的20列创建了rands CSV。(ranfile1) 和100,000行的方案。 I created a code up to the third trench without the "D".
randfile1=np.random.rand(20,100000)
spots = [0.0211,0.0188,0.0184,0.0187,0.0189,0.0195,0.0201,0.0205,0.0208,0.02120,0.0215,0.0218,0.0221,0.0224,0.0227,0.0229,0.0232,0.0235,0.0238,0.0241]
A = []
B = []
C = []
D = []
a = randfile1[randfile1 < 0.25].sum() * 5
A.append(a)
b = (randfile1[np.logical_and(0.25 <= randfile1, randfile1 < 0.5)] - 0.25).sum() * 5
B.append(b)
a = np.logical_and(0.25 < randfile1, randfile1 < 0.5).sum() * 1.25
A.append(a)
c = (randfile1[np.logical_and(0.5 <= randfile1, randfile1 < 0.75)] - 0.5).sum() * 5
C.append(c)
b = np.logical_and(0.5 < randfile1, randfile1 < 0.75).sum() * 1.25
B.append(b)
a = np.logical_and(0.5 < randfile1, randfile1 < 0.75).sum() * 1.25
A.append(a)
d = (randfile1[np.logical_and(0.75 <= randfile1, randfile1 < 1)] - 0.5).sum() * 5
D.append(d)
c = np.logical_and(0.75 < randfile1, randfile1 < 1).sum() * 1.25
C.append(c)
b = np.logical_and(0.75 < randfile1, randfile1 < 1).sum() * 1.25
B.append(b)
a += np.logical_and(0.75 < randfile1, randfile1 < 1).sum() * 1.25
A.append(a)
答案 0 :(得分:0)
您要在此处实现的目标可以通过高级索引,numpy数组上的条件以及Numpy的逻辑运算符完成。
import numpy as np
rand_data = np.random.rand(1, 40) # Generate 40 random number
A = rand_data[rand_data < 0.25].sum() * 5 # Advanced indexing is in use here
# Get the ones between 0 and 0.25 and multiply the sum with 5
# Get the ones larger than 0.25 and smaller than 0.5 apply logical-and to indices
# Get the sum of the elements in those indices and substract 0.25 from each of them
# Finally multiply the sum with 5
B = (rand_data[np.logical_and(0.25 <= rand_data, rand_data < 0.5)] - 0.25).sum() * 5
# We are interested in the count of values between 0.25 and 0.5
# So no advanced indexing here just get the count on binary values using the sum
# and multiply with 0.25 * 5
A += np.logical_and(0.25 < rand_data, rand_data < 0.5).sum() * 1.25
C = (rand_data[np.logical_and(0.5 <= rand_data, rand_data < 0.75)] - 0.5).sum() * 5
B += np.logical_and(0.5 < rand_data, rand_data < 0.75).sum() * 1.25
A += np.logical_and(0.5 < rand_data, rand_data < 0.75).sum() * 1.25
print(A)
print(B)
print(C)