Recipe: How to create a new column based on a condition in Python?
DATA MUNGING DATA CLEANING PYTHON

How to create a new column based on a condition in Python?

This recipe helps you create a new column based on a condition in Python
In [1]:
## How to create a new column based on a condition in Python
def Kickstarter_Example_81():
    print()
    print(format('How to create a new column based on a condition in Python','*^82'))

    import warnings
    warnings.filterwarnings("ignore")

    # load libraries
    import pandas as pd
    import numpy as np

    # Make a dataframe
    data = {'name': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy'],
            'age': [42, 52, 63, 24, 73],
            'preTestScore': [4, 24, 31, 2, 3],
            'postTestScore': [25, 94, 57, 62, 70]}

    df = pd.DataFrame(data, columns = ['name', 'age', 'preTestScore', 'postTestScore'])
    print(); print(df)

    # Create a new column called df.elderly where the value is yes
    df['elderly@50'] = np.where(df['age']>=50, 'yes', 'no')
    df['elderly@60'] = np.where(df['age']>=60, 'yes', 'no')
    df['elderly@70'] = np.where(df['age']>=70, 'yes', 'no')

    # View the dataframe
    print(); print(df)

Kickstarter_Example_81()
************How to create a new column based on a condition in Python*************

    name  age  preTestScore  postTestScore
0  Jason   42             4             25
1  Molly   52            24             94
2   Tina   63            31             57
3   Jake   24             2             62
4    Amy   73             3             70

    name  age  preTestScore  postTestScore elderly@50 elderly@60 elderly@70
0  Jason   42             4             25         no         no         no
1  Molly   52            24             94        yes         no         no
2   Tina   63            31             57        yes        yes         no
3   Jake   24             2             62         no         no         no
4    Amy   73             3             70        yes        yes        yes


Stuck at work?
Can't find the recipe you are looking for. Let us know and we will find an expert to create the recipe for you. Click here
Companies using this Recipe
2 developers from Infosys
1 developer from Fidelity Investments
1 developer from MudraCircle
1 developer from Wipro
1 developer from Altimetrik
1 developer from Fundtech
1 developer from KPMG
1 developer from Renovite Technologies
1 developer from YASH Technologies
1 developer from ANAC