Reputation: 151
I have a data frame, say :
Name Visits 0 Z 0 1 A 0 2 B 1 3 C 1 4 D 0 5 E 0
Now, I made a list with those names whose visits are 0, so it has Z, A, D, and E. Now, I randomly choose 2 names from these 4. Then, I want to increase the visits of these 2 people by 1. How do I reference only these 2 names, access their corresponding visits and alter it? [In python, Pandas] Thank you!
Upvotes: 1
Views: 75
Reputation: 323396
Try random.choice
from number then assign value by index
df.loc[np.random.choice(df.index[df.Visits==0],2),'Visits'] += 1
df
Out[95]:
Name Visits
0 Z 1
1 A 0
2 B 1
3 C 1
4 D 0
5 E 0
Upvotes: 1
Reputation: 20689
If you already have list of who visited 0 times you can use pd.Series.isin
to create a boolean mask for boolean indexing then increase corresponding values by 1
vals = ['Z', 'A', 'D', 'E']
m = df['Name'].isin(vals)
df.loc[m, 'Visits']+=1
# This only increases Z, A, D, E visits by 1
Upvotes: 1