Home > OS >  Using multiple conditionals including strings and integers
Using multiple conditionals including strings and integers

Time:09-26

I'm having hard time figuring out what kind of conditionals and/or statements should I use in order to achieve the following:

I need to multiply goals scored depending the difference in rank_home & rank_away:

  • If rank is lower than opponent: goals_scored * 0.15
  • If rank is equal as opponent: goals_scored * 0.30
  • If rank is higher than opponent: goals_scored * 0.45

Example: If I want to calculate the points for Ducks (index position 0), I would do:
home_goals * 0.15 because rank_away (Frogs) is lower than rank_home (Ducks)

    home_team away_team   rank_home  rank_away  home_goals  away_goals
0   Ducks     Frogs       1          2          4           1
1   Frogs     Eagles      3          3          6           3
2   Eagles    Ducks       2          1          5           5

CodePudding user response:

IIUC, you can use numpy.sign to get the sign of the differencce in rank, use it to map from a dictionary of factors:

factors = {-1: 0.15, 0: 0.30, 1: 0.45}
sign = np.sign(df['rank_home'].sub(df['rank_away']))

df['home_points'] = df['home_goals'].mul(sign.map(factors))

output:

  home_team away_team  rank_home  rank_away  home_goals  away_goals  home_points
0     Ducks     Frogs          1          2           4           1         0.60
1     Frogs    Eagles          3          3           6           3         1.80
2    Eagles     Ducks          2          1           5           5         2.25

CodePudding user response:

here is one way to do it using numpy.select

#define the conditions
cond1 = df['rank_home'] < df['rank_away']
cond2 = df['rank_home'] == df['rank_away']
cond3 = df['rank_home'] > df['rank_away']

# using np.select, assign the weight to each of the condition, 1 being default
# and multiple by home goals to get points
df['points']=np.select([cond1, cond2, cond3],
         [0.15, 0.30, 0.45],
         1) * df['home_goals']
df
    home_team   away_team   rank_home   rank_away   home_goals  away_goals  points
0   Ducks       Frogs               1            2           4           1  0.60
1   Frogs       Eagles              3            3           6           3  1.80
2   Eagles      Ducks               2            1           5           5  2.25
  • Related