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!
Here is a posible solution:
df.visit[df.visit == 0] += 1
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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.