StatsConfused
StatsConfused

Reputation: 43

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.

Upvotes: 2

Views: 125

Answers (1)

mozway
mozway

Reputation: 260640

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')

Upvotes: 2

Related Questions