1

I have this Pandas dataframe:

enter image description here

This is some fictional data about games of cricket played between two countries. I want to set the value of column winner based on this simple logic:

if country_1_runs == country_2_runs:
    winner = 3
elif country_1_runs > country_2_runs:
    winner = 1
else:
    winner = 2

I know about map and apply methods in Pandas. But I'm not certain if they allow conditional expressions like the above.

2 Answers 2

4

Use numpy.select:

m1 = df.country_1_runs == df.country_2_runs
m2 = df.country_1_runs > df.country_2_runs

df['winner'] = np.select([m1, m2], [3, 1], default=2)
Sign up to request clarification or add additional context in comments.

2 Comments

This is a really elegant solution.
@RodrikTheReader - Yes, I agree.
0

You can try

df['winner'] = np.where(df['country_1_runs'] == df['country_2_runs'], 3, 
    np.where(df['country_1_runs']> df['country_2_runs'], 1, 2))

Comments

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.