1

I have this r code that that does a simple if-else function to create a new binary variable from two other series.

df_train$TeamOnOffense = ifelse(df_train$PossessionTeam == df_train$HomeTeamAbbr, "home", "away")

However, my project is being done in Python and I have never used python before now so I have a very limited understanding of python coding. I tried using this code, but it didn't seem to work, just made every observation "away".

def OffTeam(offense):
    team = df_train['PossessionTeam']

    if offense in team:
        return 'Home'
    else:
        return 'Away'

df_train['TeamOnOffense'] = df_train['HomeTeamAbbr'].apply(OffTeam)

How would I do the ifelse statement I have from r using Python.

Edit: This question is not a duplicate of the cited question! This one is looking for an index-by-index equality of two series, while the other is looking for pre-determined values. Please unlock it.

FatihAkici
  • 4,679
  • 2
  • 31
  • 48
JareBear
  • 37
  • 1
  • 5
  • This question is not a duplicate of the cited question! This one is looking for an index-by-index equality of two series, while the other is looking for pre-determined values. Please unlock it. – FatihAkici Oct 21 '19 at 00:59
  • 1
    The answer should be: `df_train['TeamOnOffense'] = ['home' if a==b else 'away' for (a,b) in zip(df_train['HomeTeamAbbr'], df_train['HomeTeamAbbr'])]`. Writing from my phone and couldn't test, please comment if it doesn't work. – FatihAkici Oct 21 '19 at 01:01

0 Answers0