The Wayback Machine - https://web.archive.org/web/20241005212127/https://www.geeksforgeeks.org/using-dictionary-to-remap-values-in-pandas-dataframe-columns/
Open In App

Using dictionary to remap values in Pandas DataFrame columns

Last Updated : 11 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

While working with data in Pandas in Python, we perform a vast array of operations on the data to get the data in the desired form. One of these operations could be that we want to remap the values of a specific column in the DataFrame. Let’s discuss several ways in which we can do that.

Creating Pandas DataFrame to remap values

Given a Dataframe containing data about an event, remap the values of a specific column to a new value.

Python
# importing pandas as pd
import pandas as pd

# Creating the DataFrame
df = pd.DataFrame({'Date': ['10/2/2011', '11/2/2011', '12/2/2011', '13/2/2011'],
                   'Event': ['Music', 'Poetry', 'Theatre', 'Comedy'],
                   'Cost': [10000, 5000, 15000, 2000]})

# Print the dataframe
print(df)

Output:

Output

Remap values in Pandas columns using replace() function

Now we will remap the values of the ‘Event’ column by their respective codes using replace() function. 

Python
# Create a dictionary using which we
# will remap the values
dict = {'Music' : 'M', 'Poetry' : 'P', 'Theatre' : 'T', 'Comedy' : 'C'}

# Print the dictionary
print(dict)

# Remap the values of the dataframe
df.replace({"Event": dict})

Output : 

Output

Output

Remap values in Pandas DataFrame columns using map() function 

Now we will remap the values of the ‘Event’ column by their respective codes using map() function. 

Python
# Create a dictionary using which we
# will remap the values
dict = {'Music': 'M', 'Poetry': 'P', 'Theatre': 'T', 'Comedy': 'C'}

# Print the dictionary
print(dict)

# Remap the values of the dataframe
df['Event'] = df['Event'].map(dict)

# Print the DataFrame after modification
print(df)

Output: 

Output

Output

Using dictionary to remap values in Pandas DataFrame columns – FAQs

How to Replace Values in a Pandas Series Using a Dictionary

To replace values in a pandas Series based on a dictionary where the keys represent the current values and the values represent the new values, you can use the replace() method:

import pandas as pd

# Example Series
series = pd.Series([1, 2, 3, 4, 1, 2, 3, 4])

# Dictionary mapping for replacement
replacement_dict = {1: 'one', 2: 'two', 3: 'three', 4: 'four'}

# Replace values in the Series
series_replaced = series.replace(replacement_dict)
print(series_replaced)

How to Convert Dictionary to DataFrame with Keys as Columns

To convert a dictionary into a DataFrame where dictionary keys become column names and values become the data in the columns, you can simply pass the dictionary to the DataFrame constructor:

# Dictionary with lists as values
data_dict = {
'A': [1, 2, 3],
'B': [4, 5, 6],
'C': [7, 8, 9]
}

# Convert to DataFrame
df = pd.DataFrame(data_dict)
print(df)

How to Rename a Column in Pandas Based on Dictionary

To rename columns in a DataFrame using a dictionary where the current column names are keys and the new names are values, use the rename() method with the columns parameter:

# DataFrame
df = pd.DataFrame({
'X': [1, 2],
'Y': [3, 4]
})

# Dictionary for renaming columns
rename_dict = {'X': 'New_X', 'Y': 'New_Y'}

# Rename columns
df_renamed = df.rename(columns=rename_dict)
print(df_renamed)

How to Remap Column Names in Pandas

Remapping column names can be done similarly by using the rename() method. It’s particularly useful when only some of the columns need to be renamed, and it aligns well with the renaming based on a dictionary:

# Continuing with the previous example
remap_dict = {'New_X': 'A', 'New_Y': 'B'}
df_remap = df_renamed.rename(columns=remap_dict)
print(df_remap)

How to Convert Column Values to Dictionary in Pandas

To convert the values of a DataFrame column to a dictionary where indices become keys, use the to_dict() method on the Series:

# Convert a single DataFrame column to a dictionary
column_dict = df['A'].to_dict()
print(column_dict)

# To convert the entire DataFrame to a dictionary of dictionaries
full_dict = df.to_dict()
print(full_dict)


Previous Article
Next Article

Similar Reads

Wand remap() function in Python
The Remap Effect replaces all pixels with the closest matching pixel found in the affinity reference image. remap() rebuild image palette with closest color from given affinity image. Syntax: wand.image.remap(affinity, method) Parameters : Parameter Input Type Description affinity BaseImage reference image. method basestring dither method. See DITH
1 min read
Pandas DataFrame assign() Method | Create new Columns in DataFrame
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages, making importing and analyzing data much easier. The Dataframe.assign() method assigns new columns to a DataFrame, returning a new object (a copy) with the new columns added to the original one
4 min read
Drop rows from Pandas dataframe with missing values or NaN in columns
Pandas provides various data structures and operations for manipulating numerical data and time series. However, there can be cases where some data might be missing. In Pandas missing data is represented by two value: None: None is a Python singleton object that is often used for missing data in Python code. NaN: NaN (an acronym for Not a Number),
4 min read
Sort rows or columns in Pandas Dataframe based on values
In this article, Let's discuss how to Sort rows or columns in Pandas Dataframe based on values. Pandas sort_values() method sorts a data frame in Ascending or Descending order of passed Column. It's different than the sorted Python function since it cannot sort a data frame and particular column cannot be selected. Syntax: DataFrame.sort_values(by,
7 min read
Get minimum values in rows or columns with their index position in Pandas-Dataframe
Let’s discuss how to find minimum values in rows & columns of a Dataframe and also their index position. a) Find the minimum value among rows and columns : Dataframe.min() : This function returns the minimum of the values in the given object. If the input is a series, the method will return a scalar which will be the minimum of the values in the se
4 min read
Count the NaN values in one or more columns in Pandas DataFrame
Let us see how to count the total number of NaN values in one or more columns in a Pandas DataFrame. In order to count the NaN values in the DataFrame, we are required to assign a dictionary to the DataFrame and that dictionary should contain numpy.nan values which is a NaN(null) value. Consider the following DataFrame. # importing the modules impo
2 min read
How to Drop Columns with NaN Values in Pandas DataFrame?
Nan(Not a number) is a floating-point value which can't be converted into other data type expect to float. In data analysis, Nan is the unnecessary value which must be removed in order to analyze the data set properly. In this article, we will discuss how to remove/drop columns having Nan values in the pandas Dataframe. We have a function known as
3 min read
Split dataframe in Pandas based on values in multiple columns
In this article, we are going to see how to divide a dataframe by various methods and based on various parameters using Python. To divide a dataframe into two or more separate dataframes based on the values present in the column we first create a data frame. Creating a DataFrame for demonestration C/C++ Code # importing pandas as pd import pandas a
3 min read
Find maximum values & position in columns and rows of a Dataframe in Pandas
In this article, we are going to discuss how to find the maximum value and its index position in columns and rows of a Dataframe. Create Dataframe to Find max values & position of columns or rows C/C++ Code import numpy as np import pandas as pd # List of Tuples matrix = [(10, 56, 17), (np.NaN, 23, 11), (49, 36, 55), (75, np.NaN, 34), (89, 21,
4 min read
Pandas DataFrame to_dict() Method | Convert DataFrame to Dictionary
Python is a great language for doing data analysis because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.  Pandas .to_dict() method is used to convert a DataFrame into a dictionary of series or list-like data type depending on the orient parameter. Exam
3 min read
Replace values of a DataFrame with the value of another DataFrame in Pandas
In this article, we will learn how we can replace values of a DataFrame with the value of another DataFrame using pandas. It can be done using the DataFrame.replace() method. It is used to replace a regex, string, list, series, number, dictionary, etc. from a DataFrame, Values of the DataFrame method are get replaced with another value dynamically.
4 min read
Python | Pandas DataFrame.fillna() to replace Null values in dataframe
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Sometimes csv file has null values, which are later displayed as NaN in Data Frame. Just like the pandas dropna() method manages and rem
5 min read
Mapping external values to dataframe values in Pandas
Mapping external values to a dataframe means using different sets of values to add to that dataframe by keeping the keys of the external dictionary as same as the one column of that dataframe. To add external values to dataframe, we use a dictionary that has keys and values which we want to add to the dataframe. By adding external values in the dat
3 min read
Highlight the negative values red and positive values black in Pandas Dataframe
Let's see various methods to Highlight the positive values red and negative values black in Pandas Dataframe.First, Let's make a Dataframe: C/C++ Code # Import Required Libraries import pandas as pd import numpy as np # Create a dictionary for the dataframe dict = { 'Name': ['Sukritin', 'Sumit Tyagi', 'Akriti Goel', 'Sanskriti', 'Abhishek Jain'], '
3 min read
Split a String into columns using regex in pandas DataFrame
Given some mixed data containing multiple values as a string, let's see how can we divide the strings using regex and make multiple columns in Pandas DataFrame. Method #1: In this method we will use re.search(pattern, string, flags=0). Here pattern refers to the pattern that we want to search. It takes in a string with the following values: \w matc
3 min read
Highlight Pandas DataFrame's specific columns using applymap()
Let us see how to highlight elements and specific columns of a Pandas DataFrame. We can do this using the applymap() function of the Styler class. Styler.applymap() Syntax : Styler.applymap(self, func, subset = None, **kwargs) Parameters : func : takes a scalar and returns a scalar. subset : valid indexer to limit data to before applying the functi
2 min read
Highlight Pandas DataFrame's specific columns using apply()
Let us see how to highlight specific columns of a Pandas DataFrame. We can do this using the apply() function of the Styler class. Styler.apply() Syntax : Styler.apply(func, axis = 0, subset = None, **kwargs) Parameters : func : function should take a Series or DataFrame (depending on-axis), and return an object with the same shape. Must return a D
2 min read
Python | Delete rows/columns from DataFrame using Pandas.drop()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages which makes importing and analyzing data much easier. In this article, we will how to delete a row in Excel using Pandas as well as delete a column from DataFrame using Pandas. Pandas Data
4 min read
Select Rows & Columns by Name or Index in Pandas DataFrame using [ ], loc & iloc
Indexing in Pandas means selecting rows and columns of data from a Dataframe. It can be selecting all the rows and the particular number of columns, a particular number of rows, and all the columns or a particular number of rows and columns each. Indexing is also known as Subset selection. Creating a Dataframe to Select Rows & Columns in Pandas
10 min read
Difference of two columns in Pandas dataframe
Difference of two columns in pandas dataframe in Python is carried out by using following methods : Method #1 : Using ” -” operator. import pandas as pd # Create a DataFrame df1 = { 'Name':['George','Andrea','micheal', 'maggie','Ravi','Xien','Jalpa'], 'score1':[62,47,55,74,32,77,86], 'score2':[45,78,44,89,66,49,72]} df1 = pd.DataFrame(df1,columns=
2 min read
Split a text column into two columns in Pandas DataFrame
Let's see how to split a text column into two columns in Pandas DataFrame. Method #1 : Using Series.str.split() functions. Split Name column into two different columns. By default splitting is done on the basis of single space by str.split() function. # import Pandas as pd import pandas as pd # create a new data frame df = pd.DataFrame({'Name': ['J
3 min read
Getting frequency counts of a columns in Pandas DataFrame
Given a Pandas dataframe, we need to find the frequency counts of each item in one or more columns of this dataframe. This can be achieved in multiple ways: Method #1: Using Series.value_counts() This method is applicable to pandas.Series object. Since each DataFrame object is a collection of Series object, we can apply this method to get the frequ
2 min read
Show all columns of Pandas DataFrame in Jupyter Notebook
In this article, we will discuss how to show all the columns of a Pandas DataFrame in a Jupyter notebook using Python. Show All Columns and Rows in a Pandas DataFrame Pandas have a very handy method called the get.option(), by this method, we can customize the output screen and work without any inconvenient form of output. Pandas set_option() is us
3 min read
Conditional operation on Pandas DataFrame columns
Suppose you have an online store. The price of the products is updated frequently. While calculating the final price on the product, you check if the updated price is available or not. If not available then you use the last price available. Solution #1: We can use conditional expression to check if the column is present or not. If it is not present
4 min read
How to widen output display to see more columns in Pandas dataframe?
In Python, if there are many more number of columns in the dataframe, then not all the columns will be shown in the output display. So, let's see how to widen output display to see more columns. Method 1: Using pandas.set_option() function. This function is used to set the value of a specified option. Syntax: pandas.set_option(pat, value) Returns:
2 min read
Get the number of rows and number of columns in Pandas Dataframe
Pandas provide data analysts a variety of pre-defined functions to Get the number of rows and columns in a data frame. In this article, we will learn about the syntax and implementation of few such functions. Method 1: Using df.axes() Method axes() method in pandas allows to get the number of rows and columns in a go. It accepts the argument '0' fo
3 min read
Apply a function to single or selected columns or rows in Pandas Dataframe
In this article, we will learn different ways to apply a function to single or selected columns or rows in Dataframe. We will use Dataframe/series.apply() method to apply a function. Apply a function to single row in Pandas DataframeHere, we will use different methods to apply a function to single rows by using Pandas dataframe. First lets create a
5 min read
Concatenate two columns of Pandas dataframe
Let's discuss how to Concatenate two columns of dataframe in pandas python. We can do this by using the following functions : concat() append() join() Example 1 : Using the concat() method. # importing the module import pandas as pd # creating 2 DataFrames location = pd.DataFrame({'area': ['new-york', 'columbo', 'mumbai']}) food = pd.DataFrame({'fo
1 min read
Count the number of rows and columns of a Pandas dataframe
Pandas allow us to get the shape of the Dataframe by counting the number of rows and columns in the Dataframe. You can try various approaches to learn to count the number of rows and columns in a Pandas. Example: Input: {'name': ['Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura'], 'score': [98, 80, 60, 85, 49, 92], 'age': [20, 25, 22, 24
4 min read
Count the number of rows and columns of Pandas dataframe
In this article, we'll see how we can get the count of the total number of rows and columns in a Pandas DataFrame. There are different methods by which we can do this. Let's see all these methods with the help of examples. Example 1: We can use the dataframe.shape to get the count of rows and columns. dataframe.shape[0] and dataframe.shape[1] gives
2 min read