Home »
Python »
Python Programs
Pandas replace multiple values one column
Given a pandas dataframe, we have to replace multiple values one column.
By Pranit Sharma Last updated : October 03, 2023
Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.
A dictionary key can have any type of data as its value, for example, a list, tuple, string, or dictionary itself. Dictionaries are used to store heterogeneous data. The data is stored in key:value pair. A dictionary is a collection that is mutable and ordered in nature and does not allow duplicates which mean there are unique keys in a dictionary.
Problem statement
Suppose we are given a DataFrame with multiple columns and we need to replace a few of these columns with some other values in one go.
Replacing multiple values one column
For this purpose, we will use the concept of a dictionary, we will first create a DataFrame and then we will replace the column by passing a dictionary inside replace method. In this dictionary, we will pass all the values in form of column values and the keys will represent the new values.
Let us understand with the help of an example,
Python program to replace multiple values one column
# Importing pandas package
import pandas as pd
# Creating a dictionary
d = {'x': ['Good','Better','Best']}
# Creating a DataFrame
df = pd.DataFrame(d)
# Display original DataFrame
print("Original DataFrame 1:\n",df,"\n")
# Replacing the column x
df = df.replace({'x' : { 'Good' : 1, 'Better' : 2, 'Best' : 3 }})
# Display modified DataFrame
print("Modified DataFrame:\n",df)
Output
The output of the above program is:
Python Pandas Programs »