Change a percentage of dataframe column values according to the value of another column

Viewed 29

I have a dataframe similar to the one below, in which activities assume binary values representing whether they require a doctor:

d = {'activity': ['Check-up', 'Assessment', 'Medication', 'Medication', 'Medication'], 'doctor_requirement': [1, 0,0,0,0]}
df = pd.DataFrame(data=d)
df
    activity    doctor_requirement
0   Check-up    1
1   Assessment  0
2   Medication  0
3   Medication  0
4   Medication  0

I would like to consider that a percentage of 'Medication' activities require a doctor. That is, to assign binary 1 to doctor_requirement for a percentage of 'Medication' visits. For instance, such that 50% of the activity 'Medication' requires a doctor (i.e. doctor_requirement = 1).

I would greatly appreciate your help, I've been looking online and can't seem to find how to apply such a condition. Thanks in advance!

1 Answers

If you'd like a 50% chance then you can use:

df.loc[df['activity']=='Medication','doctor_requirement'] = np.random.choice([0,1],(df['activity']=='Medication').sum())

If you wish to contorl the probabilities for 0 and 1s, you can use np.random.choice's p parameter to specify odds.

df.loc[df['activity']=='Medication','doctor_requirement'] = np.random.choice([0,1],(df['activity']=='Medication').sum(),p=[0.99,0.01])
Related