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

How to insert a new column based on condition in 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

0
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

Relevant Projects

Data Science Project-All State Insurance Claims Severity Prediction
Data science project in R to develop automated methods for predicting the cost and severity of insurance claims.

Perform Time series modelling using Facebook Prophet
In this project, we are going to talk about Time Series Forecasting to predict the electricity requirement for a particular house using Prophet.

Predict Credit Default | Give Me Some Credit Kaggle
In this data science project, you will predict borrowers chance of defaulting on credit loans by building a credit score prediction model.

Data Science Project in Python on BigMart Sales Prediction
The goal of this data science project is to build a predictive model and find out the sales of each product at a given Big Mart store.

Human Activity Recognition Using Smartphones Data Set
In this deep learning project, you will build a classification system where to precisely identify human fitness activities.

Build an Image Classifier for Plant Species Identification
In this machine learning project, we will use binary leaf images and extracted features, including shape, margin, and texture to accurately identify plant species using different benchmark classification techniques.

Solving Multiple Classification use cases Using H2O
In this project, we are going to talk about H2O and functionality in terms of building Machine Learning models.

Credit Card Fraud Detection as a Classification Problem
In this data science project, we will predict the credit card fraud in the transactional dataset using some of the predictive models.

Data Science Project-TalkingData AdTracking Fraud Detection
Machine Learning Project in R-Detect fraudulent click traffic for mobile app ads using R data science programming language.

Predict Census Income using Deep Learning Models
In this project, we are going to work on Deep Learning using H2O to predict Census income.