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

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

This recipe helps you insert a new column based on condition in Python
In [1]:
## How to insert a new column based on condition in Python
def Kickstarter_Example_80():
    print()
    print(format('How to insert a new column based on condition in Python','*^82'))
    import warnings
    warnings.filterwarnings("ignore")
    # load libraries
    import pandas as pd
    import numpy as np
    # Create an example dataframe
    raw_data = {'student_name': ['Miller', 'Jacobson', 'Bali', 'Milner', 'Cooze', 'Jacon', 'Ryaner', 'Sone', 'Sloan', 'Piger', 'Riani', 'Ali'],
                'test_score': [76, 88, 84, 67, 53, 96, 64, 91, 77, 73, 52, np.NaN]}
    df = pd.DataFrame(raw_data, columns = ['student_name', 'test_score'])
    print(); print(df)
    # Create a function to assign letter grades
    grades = []
    for row in df['test_score']:
        if row > 95:    grades.append('A')
        elif row > 90:  grades.append('A-')
        elif row > 85:  grades.append('B')
        elif row > 80:  grades.append('B-')
        elif row > 75:  grades.append('C')
        elif row > 70:  grades.append('C-')
        elif row > 65:  grades.append('D')
        elif row > 60:  grades.append('D-')
        else:           grades.append('Failed')
    # Create a column from the list
    df['grades'] = grades
    # View the new dataframe
    print(); print(df)
Kickstarter_Example_80()
*************How to insert a new column based on condition in Python**************

   student_name  test_score
0        Miller        76.0
1      Jacobson        88.0
2          Bali        84.0
3        Milner        67.0
4         Cooze        53.0
5         Jacon        96.0
6        Ryaner        64.0
7          Sone        91.0
8         Sloan        77.0
9         Piger        73.0
10        Riani        52.0
11          Ali         NaN

   student_name  test_score  grades
0        Miller        76.0       C
1      Jacobson        88.0       B
2          Bali        84.0      B-
3        Milner        67.0       D
4         Cooze        53.0  Failed
5         Jacon        96.0       A
6        Ryaner        64.0      D-
7          Sone        91.0      A-
8         Sloan        77.0       C
9         Piger        73.0      C-
10        Riani        52.0  Failed
11          Ali         NaN  Failed


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 LTI
1 developer from C-DAC
1 developer from Dell EMC
1 developer from HCL
1 developer from Inmet Technology Solution
1 developer from Microsoft
1 developer from SAP
1 developer from Vodafone
1 developer from Altimetrik
1 developer from Cognizant