Creating a loop for a new column of values out of existing values

Viewed 50

I am looking to create a new column in a data frame that indicates if the game ended in a home victory, away victory or a draw.

this is the code i am currently using:

for value in df2:
    if value in df2['home_goals'] > df2['away_goals']:
        df2['result'] = 'H'
    elif value in df2['home_goals'] < df2['away_goals']:
        df2['result'] = 'A'
    else:
        df2['result'] = 'D'

This is the output.

              Home Team       Away Team home_goals away_goals result
Season                                                              
2018-2019       Man Utd       Leicester          2          1      D
2018-2019     Newcastle           Spurs          1          2      D
2018-2019   Bournemouth         Cardiff          2          0      D
2018-2019        Fulham  Crystal Palace          0          2      D
2018-2019  Huddersfield         Chelsea          0          3      D

As you can see rather showing that the Home team or away team has won in that scenario it is showing all of the results as draws.

Can someone please enlighten me in where I have gone wrong?

Thanks

4 Answers

A pythonic way of doing it could be,

import numpy as np

df2['result'] = np.where(df2['home_goals'] > df2['away_goals'], 'H', 
                         np.where(df2['home_goals'] < df2['away_goals'], 'A', 'D'))

using chained np.where() commands.

You can use np.select here.

condlist = [
    df2["home_goals"] > df2["away_goals"],
    df2["home_goals"] < df2["away_goals"],
]
choicelist = ["H", "A"]
df2["result"] = np.select(condlist, choicelist, "D")

With np.select you can have arbitrary number of conditions

condlist = [cond1, ..., condn]
choicelist = [choice1, ..., choicen]
# Here mapping is as follows:
# cond1 ⟶ choice1
# ...
# condn ⟶ choicen
np.select(condlist, choicelist, default='your_default_value')

Similar to your approach is to use the row-wise apply function on the dataframe

df = pd.DataFrame({'home':[2,1,0,2],'away':[1,3,1,2]})

def fun(x):
    if x['home']>x['away']:   return 'H'
    elif x['home']<x['away']: return 'A'
    else : return 'D'

df['result'] = df.apply(fun,axis=1)

enter image description here

You can also use apply() or iterrows() to loop over, in your code values in might be the cause so remove it.

def filter(row):
  result =''
  # Removed values in
  if row['home_goals'] > row['away_goals']:
    result = 'H'
  elif row['home_goals'] < row['away_goals']:
    result = 'A'
  else:
    result = 'D'
  return result

df['result'] = df.apply(filter,axis=1)
Related