'Changing the value of a Numpy Array based on a probability and the value itself

I have a 2d Numpy Array:

a = np.reshape(np.random.choice(['b','c'],4), (2,2))

I want to go through each element and, with probability p=0.2 change the element. If the element is 'b' I want to change it to 'c' and vice versa.

I've tried all sorts (looping through with enumerate, where statements) but I can't seen to figure it out.

Any help would be appreciated.



Solution 1:[1]

You could generate a random mask with the wanted probability and use it to swap the values on a subset of the array:

# select 20% of cells
mask = np.random.choice([True, False], a.shape, p=[0.2, 0.8])
# swap the values for those
a[mask] = np.where(a=='b', 'c', 'b')[mask]

example output:

array([['b', 'c'],
       ['c', 'c']], dtype='<U1')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mozway