www.slingacademy.com Open in urlscan Pro
2a06:98c1:3121::3  Public Scan

URL: https://www.slingacademy.com/article/pandas-using-dataframe-replace-method-7-examples/?utm_content=cmp-true
Submission: On October 11 via api from LU — Scanned from NL

Form analysis 2 forms found in the DOM

GET https://www.slingacademy.com

<form class="ml-4 md:ml-auto grow max-w-[600px]" action="https://www.slingacademy.com" method="get">
  <div class="relative w-full flex">
    <input type="text" name="s" required="" maxlength="30" title="Search slingacademy.com" id="search" class="w-full h-full pl-4 pr-12 py-2 rounded-full bg-zinc-700 text-white/90 focus:outline-none focus:ring-2 focus:ring-green-500"
      placeholder="Search">
    <button type="submit" class="absolute top-0 right-0 h-full w-12 flex justify-center items-center"><svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-white/90" fill="none" viewBox="0 0 24 24" stroke="currentColor">
        <path
          d="M 13 3 C 7.4889971 3 3 7.4889971 3 13 C 3 18.511003 7.4889971 23 13 23 C 15.396508 23 17.597385 22.148986 19.322266 20.736328 L 25.292969 26.707031 A 1.0001 1.0001 0 1 0 26.707031 25.292969 L 20.736328 19.322266 C 22.148986 17.597385 23 15.396508 23 13 C 23 7.4889971 18.511003 3 13 3 z M 13 5 C 17.430123 5 21 8.5698774 21 13 C 21 17.430123 17.430123 21 13 21 C 8.5698774 21 5 17.430123 5 13 C 5 8.5698774 8.5698774 5 13 5 z">
        </path>
      </svg>
    </button>
  </div>
</form>

GET https://www.slingacademy.com

<form class="mx-auto px-4 grow max-w-[800px]" action="https://www.slingacademy.com" method="get">
  <p class="my-4 text-center font-light text-sm text-zinc-500">Search tutorials, examples, and resources</p>
  <div class="relative w-full flex">
    <input type="text" name="s" required="" maxlength="30" title="Search slingacademy.com" id="search" class="w-full pl-4 pr-12 py-2 rounded-full bg-white border border-1 border-zinc-400 focus:outline-none focus:ring-2 focus:ring-green-500"
      placeholder="Search...">
    <button type="submit" class="absolute top-0 right-0 h-full w-12 flex justify-center items-center"><svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-zinc-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
        <path
          d="M 13 3 C 7.4889971 3 3 7.4889971 3 13 C 3 18.511003 7.4889971 23 13 23 C 15.396508 23 17.597385 22.148986 19.322266 20.736328 L 25.292969 26.707031 A 1.0001 1.0001 0 1 0 26.707031 25.292969 L 20.736328 19.322266 C 22.148986 17.597385 23 15.396508 23 13 C 23 7.4889971 18.511003 3 13 3 z M 13 5 C 17.430123 5 21 8.5698774 21 13 C 21 17.430123 17.430123 21 13 21 C 8.5698774 21 5 17.430123 5 13 C 5 8.5698774 8.5698774 5 13 5 z">
        </path>
      </svg>
    </button>
  </div>
</form>

Text Content

Sling S Academy A
 * Home
 * JavaScript
 * Python
 * Next.js
 * FastAPI





PANDAS

Series Pandas Series Cheat Sheet Create Pandas Series from Different Sources Add
and Insert New Elements into a Series Sorting a Series Counting Pandas Series
Elements Counting NaN & Non-NaN in Pandas Updating Series Indexes in Pandas
Convert Pandas Series to Dict Get Unique Values in Series Pandas: Access Series
Elements First/Last N in Pandas Series Clean Series with Pandas Remove
Non-numeric in Pandas Series List Indexes in Pandas Series Get List from Pandas
Series Convert Pandas Series to Dictionary Multi-Index Series in Pandas Looping
Through a Series Pandas: Memory Usage of Series/DF Pandas: Series Value Check
Pandas: Detect NaN in Series Check if Pandas Series is Empty Naming/Renaming
Pandas Series Cast Pandas Series Data Types Deep Copy of Pandas Series Convert
Pandas Series to NumPy Update Pandas Series Element Drop Item from Pandas Series
pandas.Series.xs() Explained Sum of N Series in Pandas Element-wise Subtract
Series Element-wise multiply 2 Series Divide Series by Series in Pandas
pandas.Series.floordiv() Guide Pandas: Series Modulo Operation Exponentiate 2
Pandas Series Guide: pandas.Series.combine() Understanding
pandas.Series.combine_first() Custom Rounding in Pandas Series Pandas
Series.lt() & le() Pandas Series.gt() & Series.ge() Methods Pandas: Series
Equality Check Product of Values in Pandas Series Dot Product in Pandas Pandas
Series.apply() Examples Pandas Series Aggregation pandas.Series.transform()
Guide pandas.Series.map() Explained Guide to pandas.Series.groupby() Pandas
Series rolling() In-depth Expanding Window Ops in Pandas Exponential Weight in
Pandas Exploring pandas.Series.pipe() pandas.Series.abs() Tutorial Checking
Series for All True Using pandas.Series.any() Lag-N Autocorrelation in Pandas
Understanding pandas.Series.between() pandas.Series.clip() Guide Pandas:
Correlation of Series pandas.Series.cov() Tutorial Cumulative Min/Max in Pandas
Cumulative Sum/Product with Pandas pandas.Series.diff() Guide
pandas.Series.factorize() Guide Computing Kurtosis with Pandas Min/Max in Pandas
Series Computing Series Mean in Pandas Pandas Series Median Pandas: Find Series
Mode Get N Largest Values in Pandas Get N Smallest Elements in Series
pandas.Series.pct_change() Guide pandas.Series.quantile() Guide
pandas.Series.rank() Examples Pandas Series.sem() Explained Unbiased Skew with
Pandas Pandas: Std Deviation of Series Pandas: Unbiased Variance Count Unique
Values in Series Unique Values in Pandas Series Pandas: Monotonic Series Check
Pandas: Count Unique Values pandas.Series.align() Explained
pandas.Series.case_when() Guide Removing Duplicates in Pandas pandas
Series.equals() method Pandas: Get N Elements of a Series Pandas idxmax() &
idxmin() Guide Using pandas.Series.isin() Method pandas.Series.reindex() Guide
Reindex-like Method Examples Renaming Pandas Series Indexes Pandas
Series.reset_index() Guide Advanced pandas.Series.sample() pandas.Series.take()
method pandas.Series.truncate() Explored Mastering pandas.Series.where() Using
pandas.Series.mask() Method Pandas: Prefix/Suffix for Series Filter Pandas
Series by Condition pandas.Series.bfill() Explained Drop NA/NaN from Pandas
Series pandas.Series.ffill() Explained Master pandas.Series.fillna() Pandas
Series.interpolate() Guide Series to List of Tuples Pandas: Series.replace()
Examples Pandas Series.argsort() Tutorial List of Tuples to Pandas Series
pandas.Series.reorder_levels() Sorting Pandas Series by Index pandas swaplevel()
Method pandas.Series.unstack() Guide pandas.Series.explore() Guide Pandas
searchsorted() Guide pandas.Series.repeat() Tutorial pandas .squeeze() Method
Guide Visualize Time Series with Holidays Comparing 2 Pandas Series Update
Pandas Series In Place Pandas Time Series Handling pandas.Series.asfreq() Guide
Time Series in Pandas Explained Pandas: Date Strings to Datetime Time Series
with Pandas pandas.Series.asof() Explained pandas.Series.shift() Explained
Pandas Series.resample() Explained pandas tz_convert() Explained
pandas.Series.tz_localize() Guide pandas.Series.at_time() Guide Selecting Values
with between_time() Exploring pandas.Series.cat() Working with Dates in pandas
Trimming Whitespaces in Pandas Pandas: Case Transformation
pandas.Series.str.match() Guide Pandas String Padding Guide Pandas Regex in
Series Slice Substrings in Pandas Series pandas str.slice_replace() Guide
pandas.Series.str.split() Guide Pandas: Check Series Substrings Pandas
DatetimeIndex Explained Pandas TimedeltaIndex Guide Pandas PeriodIndex Guide
Pandas: Handle DST Transitions Pandas Custom Holidays Business Hours in Pandas
Pandas Time Series Shift&Lag Time Series to datetime List Pandas Time Series
Frequency Split Time Series in Pandas pandas.Series.dt.floor() Explained Turning
Off Pandas Future Warnings pandas Series to_period() Explained
pandas.Series.convert_dtypes() pandas.Series.to_markdown() Guide Pandas Time
Series Analysis Adjusting Prices: Dividends & Splits Pandas EMA of Stock Price
Pandas: Calculating Stock RSI DataFrames DataFrame Cheat Sheet Pandas Data Types
Guide List of Dicts to DataFrame DataFrame to List of Dicts Import CSV into
DataFrame Read Excel Files with Pandas Parsing JSON to DataFrame Parse HTML
Table to DataFrame SQLite to DataFrame in Pandas Save DataFrame to CSV Save
DataFrame to Excel Select Columns by Data Type Store DataFrame in SQLite Saving
DataFrame as JSON Render DataFrame to HTML Table Serve DataFrame as REST API
Read XML into DataFrame DataFrame to XML with Pandas DataFrame to PDF with
Pandas Read Clipboard Data with Pandas Pandas & HDFStore Guide Pandas
json_normalize() Explained Selecting SQLite rows with Pandas Create & Add Data
to DataFrame Create DataFrame & Add Columns Pandas DataFrame from NumPy Array
Create DataFrame from Dict DataFrame from N Series in Pandas Listing DataFrame
Row Labels View DataFrame Column Labels Viewing Data Types in Pandas Pandas:
Multi-Type Columns? Summarizing DataFrames in Pandas Pandas DataFrame Data Types
DataFrame to NumPy Conversion Inspect DataFrame Axes Counting Rows & Columns in
Pandas Count Elements & Dimensions in DF Check Empty DataFrame in Pandas
Managing Duplicate Labels in DF Pandas: Casting DataFrame Types Guide to pandas
convert_dtypes() pandas infer_objects() Explained Deep/Shallow DataFrame Copies
Pandas: First/Last N Rows Access/Modify Cell with .at[]/.iat[] Mastering
pandas.DataFrame.loc[] pandas.DataFrame.insert() Guide Understanding
DataFrame.items() pandas.DataFrame.iterrows() Guide Get Pandas Column Position
Exploring pd.DataFrame.itertuples() Drop a Column in Pandas Pandas: Creating
DataFrame DataFrame to List of Tuples Deep Dive into DataFrame.xs()
pandas.DataFrame.get() Examples Exploring pandas.DataFrame.isin()
pandas.DataFrame.where() Guide pandas.DataFrame.mask() Tutorial Pandas
DataFrame.query() Method Element-wise Sum in Pandas Subtract DataFrames
Element-wise Pandas Elem-wise Multiplication Divide DataFrames Element-wise
Pandas Modulo of DataFrames Element-wise Exponentiation in Pandas Logarithmic
Operations in Pandas Master pandas.DataFrame.dot() Pandas lt() & le() Methods
Explained Pandas gt() & ge() Methods Guide Comparing DataFrames Element-wise
Pandas DataFrame.combine() Method pandas `combine_first()` Method Master
DataFrame.apply() in Pandas DataFrame.map() Method Explained Pandas
DataFrame.pipe() Guide Pandas DataFrame.agg() Examples Pandas
DataFrame.aggregate() DataFrame.transform() in Pandas Master DataFrame.groupby()
Pandas Rolling Window Calculations Expanding Window Calculations Pandas EW
Calculations Pandas DataFrame.abs() Explained Pandas DataFrame.all() Guide
Pandas DataFrame.any() Method Pandas DataFrame.clip() Tutorial Pairwise
Correlation in Pandas Counting Non-Null Values in DF Pandas DataFrame.cummax()
Explained Pandas DataFrame.cummin() Pandas & Google Sheets Tutorial Setting
Random Seed in Pandas Pandas DataFrame.cumprod() Guide Accessing & Modifying
Excel in OneDrive Handling Large Data with Pandas & Dask Pandas
DataFrame.cumsum() Guide Cleaning Text Data with Pandas Master DataFrame.diff()
in Pandas Pandas: Reading from S3 with Examples Web Scraping with Pandas Pandas
DataFrame.eval() Method Pandas Profiling for Data Analysis Pandas
DataFrame.kurt() Pandas & Spark Integration DataFrame.kurtosis() in Pandas
DataFrame.max() in Pandas Pandas for Geospatial Data Analysis Pandas
DataFrame.min() Guide Understanding DataFrame.mean() Pandas DataFrame.median()
Guide Pandas DataFrame.mode() guide DataFrame.pct_change() in Pandas Pandas
prod() & product() Methods DataFrame.quantile() in Pandas Data Ranks in Pandas
Pandas DataFrame.round() Explained Pandas DataFrame.sem() Explained Pandas
DataFrame.skew() Method Pandas DataFrame.sum() Examples Pandas DataFrame.std()
Explained DataFrame.var() in Pandas Counting Distinct Values in Pandas Add
Prefix/Suffix in Pandas Pandas DataFrame.align() Guide Pandas
DataFrame.at_time() Guide Using DataFrame.between_time() Dropping Labels in
Pandas DF Pandas: Remove Duplicate Rows Pandas DataFrame.duplicated() Pandas
equals() Explained Mastering DataFrame.filter() Pandas idxmax() & idxmin() Guide
Guide to DataFrame.reindex() Pandas: DataFrame.reindex_like() Renaming DataFrame
Columns DataFrame.reset_index() Guide Pandas DataFrame.sample() Guide
DataFrame.set_axis() in Pandas Pandas set_index() Method DataFrame.take() in
Pandas Pandas DataFrame.truncate() Explained Mastering DataFrame.bfill() in
Pandas DataFrame.dropna() in Pandas Pandas DataFrame.ffill() Guide Pandas
fillna() Method Examples Pandas interpolate() Explained Identify Missing Values
in DF Pandas: Detect Non-Missing Values Pandas DataFrame.replace() Guide
DataFrame.droplevel() in Pandas Pandas DataFrame.pivot() Tutorial Pandas
.pivot_table() Explained DataFrame.reorder_levels() guide Sort Pandas DataFrame
with sort_values() Pandas sort_index() Guide Pandas: nlargest() and nsmallest()
Pandas swaplevel() Explained Pandas DataFrame stack() & unstack() Mastering
DataFrame.transpose() Pandas DataFrame.melt() Tutorial Pandas DataFrame.assign()
Guide DataFrame.explode() in Pandas Pandas DataFrame.squeeze() DataFrame to
xarray in Pandas Master Pandas DataFrame.compare() Pandas DataFrame.join()
Explained Merge 2 Pandas DataFrames Pandas DataFrame.update() DataFrame.asfreq()
in Pandas Pandas DataFrame.asof() Guide DataFrame.shift() in Pandas
DataFrame.resample() Guide Pandas to_period() Explained DataFrame.to_timestamp()
Guide Understanding DataFrame.tz_convert() NumPy Type Checking with mypy Pandas
tz_localize() Guide Pandas to_string() Explained Appending Rows in DataFrame
Prepend Row to DataFrame Filter DataFrame by Conditions Pandas MultiIndex
Tutorial Iterate DataFrame Rows in Pandas Async/Await in Pandas Selecting Rows
in Pandas Selecting Columns in Pandas Swapping Columns in Pandas Change Pandas
Columns Order Changing Column Data Type in Pandas Search Rows by String Keyword
Sorting DataFrame Rows DataFrame to MongoDB Tutorial Replacing NA/NaN with Zero
in DF Create Empty DataFrame in Pandas Filter DataFrame with LIKE/NOT LIKE
Shuffling DataFrame Rows Update Cell in Pandas DataFrame Concatenate CSVs into a
DataFrame Save DataFrame to Multiple CSVs Add Column Based on Existing Ones
Checking Column Existence in DF Check Row Existence in DataFrame Dropping Unused
Levels in MultiIndex Select Columns Except Some in Pandas Split DataFrame in
Test/Train/Val Sets Indexes with Conditions in Pandas Counting Value Frequency
with Pandas Convert ISO Strings to Datetime Appending DataFrame rows to CSV
Select N Random Rows in Pandas Select Rows Between Dates Select rows by time
frame in Pandas Convert Strings to Numbers in DF Combine Columns in Pandas Print
DataFrame Without Index Print All Columns in Pandas Clear DataFrame Rows in
Pandas Pandas: Map True/False to 1/0 Filter Pandas DataFrame with regex Dropping
Non-Numerical Columns Removing Duplicates in Pandas Renaming DataFrame Columns
Dropping Columns in Pandas Dropping Columns in Pandas Drop Columns by Avg
Threshold Pandas: String Conversion Pandas: Clean Column Names Read
Authenticated CSV with Pandas Select Rows Not in Another DF Appending Footer Row
in Pandas Understanding dtype('O') in Pandas Replace NaN with Column Mean Pandas
DataFrame & Type Hints Pandas Series & Type Hints Generate Heatmap with Pandas
Pandas + Faker for Random Data Insert a Row in DataFrame Comparing 2 DataFrame
Columns Select Columns by Name Patterns Organize a Pandas Project DataFrame vs
Matrix Explained Trim Strings in DataFrame Pandas DataFrame Column Naming
Convert DataFrame to Series Concatenate Strings in DataFrame Partition Large
DataFrame Append Dict to DataFrame Replace Negative Values in DF Split DataFrame
Column Swap Rows in Pandas DataFrame Pandas: Timestamp to Datetime Filtering
DataFrame with OR Replicate DataFrame Row N Times Pandas: Auto-Increment Column
Find Closest Value in DataFrame Nested Dict to Multi-Index DF Convert DataFrame
strings to binary Creating Categorical Columns Pandas: Ordered Categories
SparseArray in Pandas Explained Combine Categorical Columns IntervalIndex in
Pandas PeriodIndex in Pandas Explained Pandas BusinessDay.is_on_offset()
CustomBusinessDay in Pandas Rolling Sample Covariance Rolling Weighted Mean with
Pandas Rolling Weighted Window with Pandas Pandas: Rolling Weighted Variance
Rolling Weighted Std Deviation Expanding Count in Pandas DF Expanding Min/Max in
Pandas Pandas cut() Function Explained Exploring Pandas qcut() Function Pandas
get_dummies() Function Pandas from_dummies() Guide Pandas lreshape() Tutorial
Pandas wide_to_long() Examples Pandas to_timedelta() Function Pandas: Business
Day DatetimeIndex Infer_freq() in Pandas Pandas Dataframe/Series Hashing Pandas:
Counting Grouped Rows Sum/Average in Pandas DataFrame Min/Max in DataFrame
Groups Count Unique Values in Groups Pandas GroupBy Day of Week Pandas DataFrame
Grouping Pandas: Product of Groups Summary Stats of DF Groups Get nth Row of
Each Group in Pandas Get Head/Tail Rows in Pandas Rank Values in Pandas Groups
Pandas: Cumulative Sum/Avg by Group Cumulative Min/Max in Pandas Pandas
Cumulative Product by Group DataFrame from a String Pandas INNER JOIN DataFrames
LEFT JOIN with Pandas Pandas: RIGHT JOIN DataFrames Pandas FULL JOIN Tutorial
Pandas: CROSS JOIN DataFrames Pandas: SELF JOIN Explained Reading CSV with
Custom Delimiter Pandas: Reading Varied CSV Rows Combine Excel Files with Pandas
Skip N Rows in Pandas CSV Dropping MultiIndex in Pivot Tables Adding Percent
Column in Pandas Pandas Pivot Table Tutorial Pandas Lag/Lead Column Tutorial
Find Frequent Value in DF Groups Combine date & time in Pandas Grouping Pandas
DataFrame Rows Pandas: Create New Column with Conditions Check Numeric Data in
DataFrame Error Fixing Fixing Pandas FutureWarning Fixing pandas Module Error
Fixing Pandas ImportError Fixing Pandas Pyarrow Warning Fixing Pandas TypeError
Fixing Pandas ValueError Fixing Pandas KeyError Fixing SettingWithCopyWarning
Fixing Pandas UnicodeDecodeError Fixing Pandas DtypeWarning Fixing Pandas
'append' Error Fixing Pandas Merge ValueError Fixing Pandas sort attribute Error
Fix Pandas 'ix' AttributeError Fixing 'pd' not Defined Error Fixing Pandas
String to Float Error Fix Pandas TypeError Fixing Pandas KeyError Fix
OutOfBoundsDatetime Error Fixing Pandas ValueError Fixing Pandas ValueError
Fixing LinAlgError: Singular Matrix Fix .str AttributeError in Python Fixing
Pandas AttributeError Fixing DataFrame not callable Pandas ValueError Fix Fixing
Pandas ValueError Fixing Pandas ValueError Fixing Pandas ValueError Fixing
Pandas TypeError Fixing Pandas Merge ValueError Fixing NumPy ValueError Fix
Pandas ValueError Fixing Pandas TypeError Fixing Pandas Index ValueError Fixing
Pandas ValueError Fixing Pandas TypeError Fixing Pandas TypeError Pandas
ValueError Fix Fix Pandas ValueError Pandas DataFrame: Group Sorting Fixing
Pandas DeprecationWarning 'str' AttributeError in Pandas Fix Pandas
AttributeError Fixing Pandas FutureWarning Fixing Pandas TypeError Fix
TypeError: datetime64 sum ops Fixing Pandas FutureWarning Fixing Pandas
AttributeError Fixing Pandas/NumPy Shape Error Fixing Pandas FutureWarning
Pandas NameError: null not defined Fixing Pandas ValueError Fixing
NDFrame.asof() Error in Pandas Fixing Pandas NameError: NaN Fixing Pandas asof()
TypeError Fixing Pandas ValueError Fixing DataFrame.applymap Warning Fixing
Pandas SparseArray TypeError Fixing Pandas NameError
Home » Pandas » Pandas: Using DataFrame.replace() method (7 examples)



PANDAS: USING DATAFRAME.REPLACE() METHOD (7 EXAMPLES)

Updated: February 20, 2024 By: Guest Contributor Post a comment
Table Of Contents
1 Introduction
2 When to Use DataFrame.replace()?
3 Preparing a Sample DataFrame
4 Example 1: Basic Replacement
5 Example 2: Replacing Multiple Values at Once
6 Example 3: Replacing Values in Specified Columns
7 Example 4: Using Regex for Replacement
8 Example 5: Replacing NaN Values
9 Example 6: Replacing with a Dictionary of Columns
10 Example 7: Advanced Replacement with a Lambda Function
11 Conclusion


INTRODUCTION

Pandas is an open source Python package that is most widely used for data
science/data analysis and machine learning tasks. It allows for manipulating
data frames, but one of its most versatile functions is the replace() method.
This tutorial will guide you through using the DataFrame.replace() method across
seven different examples, ranging from basic to advanced usage.




WHEN TO USE DATAFRAME.REPLACE()?

The replace() method in Pandas is used to replace a string, regex, list,
dictionary, series, number, etc., from a DataFrame. This could be in a single
column or the entire DataFrame. Not only does it help in data cleaning by
replacing NaN values or arbitrary numbers, but it’s also quite useful for
manipulating the data to better fit the needs of your data analysis.




PREPARING A SAMPLE DATAFRAME

Through out this tutorial, we’ll use this sample DataFrame for practice:

import pandas as pd

# Sample DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': ['a', 'b', 'c']})


EXAMPLE 1: BASIC REPLACEMENT

df.replace(1, 100)


Output:

     A  B  C
0  100  4  a
1    2  5  b
2    3  6  c


In the example above, all instances of the number 1 in the DataFrame were
replaced with 100.


EXAMPLE 2: REPLACING MULTIPLE VALUES AT ONCE

df.replace([1, 3], [100, 300])


Output:

     A  B  C
0  100  4  a
1    2  5  b
2  300  6  c


This example demonstrates how to replace multiple values at once. The first list
contains the values to be replaced, and the second list their respective
replacements.


EXAMPLE 3: REPLACING VALUES IN SPECIFIED COLUMNS

df.replace({'A': 1, 'B': 5}, 100)


Output:

     A    B  C
0  100    4  a
1    2  100  b
2    3    6  c




This code block showcases replacing values in specified columns. The dictionary
keys indicate the columns, and the values indicate the values in those columns
that are to be replaced.


EXAMPLE 4: USING REGEX FOR REPLACEMENT

df = pd.DataFrame({'A': ['1x', '2y', '3z'], 'B': ['4x', '5y', '6z'], 'C': ['ax', 'by', 'cz']})

df.replace(to_replace=r'\d', value='Digit', regex=True)


Output:

       A      B   C
0  Digitx  Digitx  ax
1  Digity  Digity  by
2  Digitz  Digitz  cz


Regular expressions (Regex) provide a powerful way to identify and replace
patterns in the data, not just exact matches. In this example, we used regex to
replace all numeric characters with the word ‘Digit’.


EXAMPLE 5: REPLACING NAN VALUES

import numpy as np

df = pd.DataFrame({'A': [np.nan, 2, np.nan], 'B': [1, np.nan, 3]})

# Replace NaN values with -1
df.replace(np.nan, -1)


Output:

     A    B
0 -1.0  1.0
1  2.0 -1.0
2 -1.0  3.0


NaN values often represent missing data. Using replace(), you can easily replace
these with a more appropriate value for further analysis, such as -1 in this
case.


EXAMPLE 6: REPLACING WITH A DICTIONARY OF COLUMNS

df.replace({'A': np.nan, 'B': 1}, -1)


Output:

     A    B
0 -1.0 -1.0
1  2.0  NaN
2 -1.0  3.0


This example demonstrates how to use a dictionary where the keys are columns,
and the values are the items to replace. It’s a powerful method for replacing
specific values across multiple columns.


EXAMPLE 7: ADVANCED REPLACEMENT WITH A LAMBDA FUNCTION

df = pd.DataFrame({'A': ['apple', 'banana', 'cherry'], 'B': ['d', 'e', 'f']})

df.replace({'A': r'^a.*'}, {'A': lambda x: x.group(0).upper()}, regex=True)


Output:

       A  B
0  APPLE  d
1 banana  e
2 cherry  f


In the most advanced example, we use a lambda function to replace values. Here,
any value in column ‘A’ that starts with ‘a’ is replaced by its uppercase
version. This example showcases the power of combining regex and lambda
functions for dynamic replacements.


CONCLUSION

The replace() method in Pandas is a highly versatile tool for data preprocessing
and cleaning. Throughout this tutorial, we’ve covered multiple ways it can be
used, from simple value replacements to complex pattern matching with regex and
lambda functions. Understanding these examples will significantly enhance your
data manipulation skills and contribute to more effective data analysis
workflows.

Next Article: Pandas: Convert a list of dicts into a DataFrame

Previous Article: Pandas: Detect non-missing values in a DataFrame

Series: DateFrames in Pandas

Pandas







Related Articles


Pandas: Remove all non-numeric elements from a Series (3 examples) How to Use
Pandas Profiling for Data Analysis (4 examples) How to Handle Large Datasets
with Pandas and Dask (4 examples) Pandas – Using DataFrame.pivot() method (3
examples) Pandas: How to ‘FULL JOIN’ 2 DataFrames (3 examples) Pandas: Select
columns whose names start/end with a specific string (4 examples) 3 ways to turn
off future warnings in Pandas How to Use Pandas for Geospatial Data Analysis (3
examples) How to Integrate Pandas with Apache Spark How to Use Pandas for Web
Scraping and Saving Data (2 examples) How to Clean and Preprocess Text Data with
Pandas (3 examples) Pandas – Using Series.replace() method (3 examples)





Search tutorials, examples, and resources



 * Resources
   * Test API
   * Datasets
 * Mobile
   * Flutter
   * Swift
   * SwiftUI
 * Databases
   * PostgreSQL
   * MySQL
   * MongoDB
 * PHP Ecosystem
   * PHP programming
   * Symfony & Doctrine
   * Laravel & Eloquent
 * JS, TS, and CSS
   * JavaScript
   * TypeScript
   * Next.js
   * Tailwind CSS
   * Node.js
   * Express.js
   * NestJS
   * Sequelize.js
   * Mongoose.js
 * Python & Data Science
   * Python
   * Pydantic
   * FastAPI
   * Django
   * SQLAlchemy
   * PyTorch
   * NumPy
   * Pandas


 * Privacy Policy
 * About Us
 * Contact

© 2024 Sling Academy
x
✕


PRIVACY & TRANSPARANTIE

slingacademy.com en onze partners vragen om jouw toestemming om je persoonlijke
gegevens te gebruiken en om informatie op je apparaat op te slaan en/of te
raadplegen. Dit omvat het gebruik van je persoonlijke gegevens voor
gepersonaliseerde advertenties en inhoud, advertentie- en inhoudsmeting,
doelgroeponderzoek en de ontwikkeling van diensten. Een voorbeeld van
gegevensverwerking kan een unieke identificatie zijn die in een cookie wordt
opgeslagen. Jouw persoonlijke gegevens kunnen worden opgeslagen, geraadpleegd en
gedeeld met 901 partners, of alleen door deze site worden gebruikt. Je kunt je
instellingen wijzigen of je toestemming op elk moment intrekken; de link
hiervoor is te vinden in onze privacy policy onderaan deze pagina. Sommige
leveranciers kunnen je persoonlijke gegevens verwerken op basis van
gerechtvaardigd belang, waar je bezwaar tegen kunt maken door je instellingen
hieronder te beheren.



Instellingen beheren Ga verder met aanbevolen cookies

Leverancierslijst | Privacy Policy