将条件中的数值数组值替换为随机数 [英] Replace numpy array value on condition with random number

查看:117
本文介绍了将条件中的数值数组值替换为随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将基于条件的数值数组中的某些值替换为随机数。

我有一个函数,50%的时间会将随机值相加:

def add_noise(noise_factor=0.5):

    chance = random.randint(1,100)
    threshold_prob = noise_factor * 100.

    if chance <= threshold_prob:
        noise = float(np.random.randint(1,100))
    else:
        noise = 0.

    return(noise)

但是当我调用numpy函数时,它会用生成的随机数替换所有匹配值:

np.place(X, X==0., add_noise(0.5))

这样做的问题是Add_Noise()只运行一次,它会替换所有的0。值和噪声值。

我尝试做的是"迭代"数字数组中的每个元素,检查条件(is it==0)。并且我希望每次都通过add_noise()生成噪声值。

我可以通过遍历每行每列的for循环来完成此操作,但有谁知道更有效的方法吗?

推荐答案

这里有一个矢量化方法-

noise_factor = 0.5 # Input param

# Get mask of zero places and the count of it. Also compute threshold
mask = X==0
c = np.count_nonzero(mask)
threshold_prob = noise_factor * 100.

# Generate noise numbers for count number of times. 
# This is where vectorization comes into the play.
nums = np.random.randint(1,100, c)

# Finally piece of the vectorization comes through replacing that IF-ELSE
# with np,where that does the same op of choosing but in a vectorized way
vals = np.where(nums <= threshold_prob, np.random.randint(1,100, c) , 0)

# Assign back into X
X[mask] = vals
额外的好处是,我们重新使用0smask进行add_noise操作,并将其分配回X。这取代了np.place的使用,并用作效率标准。

进一步提升性能

我们可以在计算numsvals的步骤中进一步优化,这些步骤使用两个随机数生成步骤,而不是执行一次,并在第二个步骤重用,如SO-

nums = np.random.randint(1,100, (2,c))
vals = np.where(nums[0] <= threshold_prob, nums[1] , 0)

这篇关于将条件中的数值数组值替换为随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆