Skip to main content
 首页 » 编程设计

python之随机生成更多比例的零python

2025年05月04日25zengkefu

我想模拟一个值介于 0 和 1 之间的变量。但我也希望这个随机变量有 80% 为零。目前我正在做以下事情:

data['response']=np.random.uniform(0,1,15000)#simulate response 
data['response']=data['response'].apply(lambda x:0 if x<0.85 else x) 

但这只会导致变量中的极值(0 和 .8+)。我希望 80% 的值为零,其余 20% 的行的值介于 0 和 1 之间。这必须随机进行。

请您参考如下方法:

这是另一个使用 numpy.random.shuffle 的

# Proportion between zeros and non-zeros 
proportion = .8 
n_non_zeros = 200 
 
# Generate fake non-zero data. 
# Inversion to ensure the range contains all the values between 0 and 1, except 0 
non_zeros = 1 - np.random.uniform(size=[n_non_zeros]) 
 
# Append [proportion / (1 - proportion)] zeros 
# to 'non_zeros' array for each non-zero 
non_zeros += [0] * int(n_non_zeros * proportion / (1 - proportion)) 
 
# Shuffle data 
np.random.shuffle(data) 
 
# 'data' now contains 200 non-zeros and 800 zeros 
# They are %20 and %80 of 1000