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)
这篇关于将条件中的数值数组值替换为随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
织梦狗教程
本文标题为:将条件中的数值数组值替换为随机数
基础教程推荐
猜你喜欢
- 在 Python 中将货币解析为数字 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
