Sepehr February 2016

Replace booleans randomly in a pandas series

I have a pandas series such as the following:

A     False
B     True
C     False
D     True
E     True
dtype: bool

that contains exactly two falses. I would like to flip one of the False values randomly to a True. Alternatively, how can I change the first or second occurrence to True. I tried the replace function but it changes everything to True. Any help is appreciated.

Edit :

Would have expected the following to do the job:

mask.ix[mask==False][np.random.randint(2)] = True

Answers


Sepehr February 2016

Can be solved by:

mask[mask.index[mask==False][np.random.randint(2)]] = True


SPKoder February 2016

A slightly more concise solution is:

mask[~mask].iloc[np.random.randint(2)] = True

Post Status

Asked in February 2016
Viewed 3,195 times
Voted 9
Answered 2 times

Search




Leave an answer