I would like to randomly swap one 0 and one 1 in a one dimensional array which contain only 0 and 1 many many times say up to N = 10^6. Here is my code for doing the swap one time.
import numpy as np
# a contains only 0 and 1
a = np.array([0,1,1,0,1,1,0,0,0,1])
# j1 random position of 0, j2 random position of 1
j1 = np.random.choice(np.where(a==0)[0])
j2 = np.random.choice(np.where(a==1)[0])
# swap
a[j1], a[j2] = a[j2], a[j1]
Since I would like to do this process many many time, at every iteration, I need to use np.where() to locate posistions of 0 and 1, which I think is not that efficient.
Is there any other approach which can be more effecient ?