Replace numpy array value on condition with random number(将条件中的数值数组值替换为随机数)
本文介绍了将条件中的数值数组值替换为随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要将基于条件的数值数组中的某些值替换为随机数。
我有一个函数,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
额外的好处是,我们重新使用0s的mask进行add_noise操作,并将其分配回X。这取代了np.place的使用,并用作效率标准。
进一步提升性能
我们可以在计算nums和vals的步骤中进一步优化,这些步骤使用两个随机数生成步骤,而不是执行一次,并在第二个步骤重用,如SO-
nums = np.random.randint(1,100, (2,c))
vals = np.where(nums[0] <= threshold_prob, nums[1] , 0)
这篇关于将条件中的数值数组值替换为随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
编程基础网
本文标题为:将条件中的数值数组值替换为随机数
基础教程推荐
猜你喜欢
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
