1

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!

3 Answers 3

1

Here is a posible solution:

df.visit[df.visit == 0] += 1
Sign up to request clarification or add additional context in comments.

Comments

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

4 Comments

this worked for me, thanks a lot! I just replaced vals with the random list containing 2 names and it worked like a charm, thanks a lot!!
Glad to help. Take a look at BEN's answer much better than mine TBH ;)
is there a way I can contact you @Ch3esteR lol please don't say no?
@YamiKanashi Yes sure through StackOverflow chat.
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

1 Comment

Edited answer as OP wanted to increase by 1. Feel free revert changes if not okay.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.