How to create a new column based on a condition in Python?
DATA MUNGING DATA CLEANING PYTHON MACHINE LEARNING RECIPES PANDAS CHEATSHEET     ALL TAGS

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

0
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

Relevant Projects

Mercari Price Suggestion Challenge Data Science Project
Data Science Project in Python- Build a machine learning algorithm that automatically suggests the right product prices.

Walmart Sales Forecasting Data Science Project
Data Science Project in R-Predict the sales for each department using historical markdown data from the Walmart dataset containing data of 45 Walmart stores.

Data Science Project - Instacart Market Basket Analysis
Data Science Project - Build a recommendation engine which will predict the products to be purchased by an Instacart consumer again.

Music Recommendation System Project using Python and R
Machine Learning Project - Work with KKBOX's Music Recommendation System dataset to build the best music recommendation engine.

Predict Employee Computer Access Needs in Python
Data Science Project in Python- Given his or her job role, predict employee access needs using amazon employee database.

Choosing the right Time Series Forecasting Methods
There are different time series forecasting methods to forecast stock price, demand etc. In this machine learning project, you will learn to determine which forecasting method to be used when and how to apply with time series forecasting example.

Data Science Project on Wine Quality Prediction in R
In this R data science project, we will explore wine dataset to assess red wine quality. The objective of this data science project is to explore which chemical properties will influence the quality of red wines.

Learn to prepare data for your next machine learning project
Text data requires special preparation before you can start using it for any machine learning project.In this ML project, you will learn about applying Machine Learning models to create classifiers and learn how to make sense of textual data.

Customer Churn Prediction Analysis using Ensemble Techniques
In this machine learning churn project, we implement a churn prediction model in python using ensemble techniques.

Zillow’s Home Value Prediction (Zestimate)
Data Science Project in R -Build a machine learning algorithm to predict the future sale prices of homes.