Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create a new Column in a Pandas DataFrame based on certain values in another column using Python?

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’.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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:

  1. 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.

  1. 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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading