How to replace multiple values in a Pandas DataFrame?
DATA MUNGING DATA CLEANING PYTHON MACHINE LEARNING RECIPES PANDAS CHEATSHEET     ALL TAGS

How to replace multiple values in a Pandas DataFrame?

How to replace multiple values in a Pandas DataFrame?

This recipe helps you replace multiple values in a Pandas DataFrame

0
In [1]:
## How to replace multiple values in a Pandas DataFrame
def Snippet_104():
    print()
    print(format('How to replace multiple values in a Pandas DataFrame','*^82'))

    import warnings
    warnings.filterwarnings("ignore")

    # load libraries
    import pandas as pd
    import numpy as np

    # Create dataframe
    raw_data = {'first_name': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy'],
                'last_name': ['Miller', 'Jacobson', 'Ali', 'Milner', 'Cooze'],
                'age': [42, 52, 36, 24, 73],
                'preTestScore': [-999, -999, -999, 2, 1],
                'postTestScore': [2, 2, -999, 2, -999]}

    df = pd.DataFrame(raw_data, columns = ['first_name', 'last_name', 'age', 'preTestScore', 'postTestScore'])
    print(); print(df)

    # Replace all values of -999 with NAN
    print(); print(df.replace(-999, np.nan))

    # Replace all values of -999 with 0
    print(); print(df.replace(-999, 0))

Snippet_104()
***************How to replace multiple values in a Pandas DataFrame***************

  first_name last_name  age  preTestScore  postTestScore
0      Jason    Miller   42          -999              2
1      Molly  Jacobson   52          -999              2
2       Tina       Ali   36          -999           -999
3       Jake    Milner   24             2              2
4        Amy     Cooze   73             1           -999

  first_name last_name  age  preTestScore  postTestScore
0      Jason    Miller   42           NaN            2.0
1      Molly  Jacobson   52           NaN            2.0
2       Tina       Ali   36           NaN            NaN
3       Jake    Milner   24           2.0            2.0
4        Amy     Cooze   73           1.0            NaN

  first_name last_name  age  preTestScore  postTestScore
0      Jason    Miller   42             0              2
1      Molly  Jacobson   52             0              2
2       Tina       Ali   36             0              0
3       Jake    Milner   24             2              2
4        Amy     Cooze   73             1              0

Relevant Projects

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.

Ecommerce product reviews - Pairwise ranking and sentiment analysis
This project analyzes a dataset containing ecommerce product reviews. The goal is to use machine learning models to perform sentiment analysis on product reviews and rank them based on relevance. Reviews play a key role in product recommendation systems.

Predict Churn for a Telecom company using Logistic Regression
Machine Learning Project in R- Predict the customer churn of telecom sector and find out the key drivers that lead to churn. Learn how the logistic regression model using R can be used to identify the customer churn in telecom dataset.

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.

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.

Machine Learning or Predictive Models in IoT - Energy Prediction Use Case
In this machine learning and IoT project, we are going to test out the experimental data using various predictive models and train the models and break the energy usage.

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.

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

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.

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.