I am still learning Python and Pandas and could use some help. I would like to create a new column in an existing DataFrame.
Current DataFrame:
bballData = {'Name':['Joel', 'Cole', 'Duncan'],
'Team':['PHI', 'ORL', 'MIA'],
'Home':['PHI', 'PHI', 'MIA'],
'Away':['ORL', 'ORL', 'POR']}
df = pd.DataFrame(bballData)
The new column will be ‘Opponent’.
Desired output:
bballDataFinal = {'Name':['Joel', 'Cole', 'Duncan'],
'Team':['PHI', 'ORL', 'MIA'],
'Home':['PHI', 'PHI', 'MIA'],
'Away':['ORL', 'ORL', 'POR'],
'Opponent':['ORL','PHI','POR']}
dfFinal = pd.DataFrame(bballDataFinal)
In order to create this new column, ‘Opponent’, I am hoping the following can be done:
- If ‘Team’ value equals ‘Home’ value then the OPPONENT should be ‘Away’ value.
In this case for player 1, Joel, his team is PHI and Home is PHI so the opponent should be the ‘Away’ value, ORL.
- If ‘Team’ value equals ‘Away’ value then the OPPONENT should be ‘Home’value.
In this case for player 2, Cole, his team is ORL and Away is ORL so the opponent should be the ‘Home’ value, PHI.
>Solution :
You can use np.select here. It evaluates multiple conditions and selects outcomes depending on which condition evaluates to True. So for example, if df['Team']==df['Home'] is True, it selects from df['Away'] etc.
import numpy as np
df['Opponent'] = np.select([df['Team']==df['Home'], df['Team']==df['Away']], [df['Away'], df['Home']], 'No opponent here')
If it’s guaranteed that opponent must be one of the two team listed, then you can use np.where. Basically, this is a binary version of np.select.
df['Opponent'] = np.where(df['Team']==df['Home'], df['Away'], df['Home'])
Output:
Name Team Home Away Opponent
0 Joel PHI PHI ORL ORL
1 Cole ORL PHI ORL PHI
2 Duncan MIA MIA POR POR