pandas
  1. pandas-dataframereplace

DataFrame.replace() - ( Pandas Data Operations and Processing )

Heading h2

Syntax

DataFrame.replace(to_replace=None, value=None, inplace=False, limit=None, regex=False, method='pad', axis=None)

Example

import pandas as pd

data = {'Name': ['John', 'Jane', 'Adam', 'Kate'],
        'Age': [27, 24, 22, 29],
        'Gender': ['Male', 'Female', 'Male', 'Female']}

df = pd.DataFrame(data)

# replace 'Male' with 'M' and 'Female' with 'F'
df.replace({'Male':'M', 'Female':'F'}, inplace=True)

print(df)

Output

   Name  Age Gender
0  John   27      M
1  Jane   24      F
2  Adam   22      M
3  Kate   29      F

Explanation

DataFrame.replace() is a method in Pandas used to replace values in a DataFrame. It takes in a dictionary or a value to replace, and a new value to replace the old value with.

In the above example, we create a simple DataFrame with the columns Name, Age, and Gender. We then use the replace() method to replace all occurrences of Male with M and all occurrences of Female with F. The inplace=True argument updates the original DataFrame with the new values.

Use

DataFrame.replace() is useful in replacing specific values in a DataFrame with new values. It can be used to clean and preprocess data before analysis.

Important Points

  • DataFrame.replace() is a method in Pandas used to replace values in a DataFrame
  • It takes in a dictionary or a value to replace, and a new value to replace the old value with
  • The inplace=True argument updates the original DataFrame with the new values

Summary

In conclusion, DataFrame.replace() is a useful method in Pandas used to replace specified values in a DataFrame with new values. It is a useful tool in cleaning and preprocessing data before analysis.

Published on: