我必须在[0,5]中生成填充了随机值的稀疏数组,其中0是缺失值。值的概率必须沿阵列变化。我这样做是这样的:
a1 = np.random.choice(range(0,6),10,p=[0.3,0,0,0,0.3,0.4])
a2 = np.random.choice(range(0,6),10,p=[0.9,0.05,0.025,0.025,0,0])
a3 = np.random.choice(range(0,6),10,p=[0.95,0.05,0,0,0,0])
np.hstack([a1,a2,a3])
>>> array([4, 4, 5, 5, 0, 4, 5, 5, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 1, 0, 0, 0, 0, 0])
这样做有一种更清洁,更统一的方式吗?
答案 0 :(得分:0)
你可以这样做:
np.hstack([(np.random.choice(range(0,6),10,p=[0.3,0,0,0,0.3,0.4])), (np.random.choice(range(0,6),10,p=[0.9,0.05,0.025,0.025,0,0])),(np.random.choice(range(0,6),10,p=[0.95,0.05,0,0,0,0]))])
它并没有真正改变任何东西,但它确实看起来更清洁,不会混淆命名空间。