1

Need a help with conditionals for pandas dataframe. Apologies in advance for the basic question or if it's covered elsewhere.

Here's the example dataframe:

employee sales revenue salary
12345    20    10000   100000 

I have a few conditions based on data which will result in salary changing.

scenarios: if sales >10 and revenue > $5,000, increase salary by 20% if sales <5 and revenue > $5,000, increase salary by 10% otherwise, do nothing.

variables:
high_sales = 10
low_sales = 5
high_revenue = 5000
big_increase = 1.2
small_increase = 1.1

I know this requires some nesting but it's not clear to me how to do it.

I want the outcome to be a dataframe with only the salary column adjusted.

Here's the code:

df['salary'] = np.where((df['sales']>=high_sales & df['revenue'] 
>=high_revenue), df['salary'] * big_increase, (df['sales']<=low_sales & 
df['revenue'] >=high_revenue), df['salary'] * small_increase, df['sales'])

Is this right?

1
  • That's why I shouldn't try editing formatting from my phone. Sorry for messing it up. Please take "here's the code" out of the bottom code block to fix the string highlighting. Commented Sep 23, 2018 at 17:27

1 Answer 1

1

With multiple conditions, it's nicer to use np.select rather than np.where:

conds = [(df.sales > 10) & (df.revenue > 5000),
         (df.sales < 5) & (df.revenue > 5000)]

choices = [df.salary * 1.2, df.salary * 1.1]

df['salary'] = np.select(conds, choices, default = df.revenue)
Sign up to request clarification or add additional context in comments.

4 Comments

Better, in my opinion: df['salary'] *= np.select(conds, [1.2, 1.1], 1).
Yeah, perhaps that is a bit nicer, thanks for pointing it out!
Thanks all. What does the "default = df.revenue" part do?
That's for the otherwise, do nothing condition that you had in your post. You can take a look at the default argument in the documentation I linked

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.