I need to replace some values in a numpy array based on a condition with a random number.
I have a function that adds a random value 50% of the time:
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)
But when I call the numpy function, it replaces all matching values with the random number generated:
np.place(X, X==0., add_noise(0.5))
The problem with this, is that add_noise() only runs once, and it replaces all the 0. values with the noise value.
What I am trying to do is "iterate" through every element in the numpy array, check the condition (is it ==0.) and I want to generate the noise value through add_noise() every time.
I could do this with a for loop going through every row and column, but does anyone know of a more efficient manner of doing it?
Aucun commentaire:
Enregistrer un commentaire