Map dataframe index using dictionary

Learn, how to pap dataframe index using dictionary in Python?
Submitted by Pranit Sharma, on November 30, 2022

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.

Problem statement

Suppose we are given the dataframe with a column of some values and with some specific indexes now we need to map the indexes in the form of a dictionary such that the indexes become the keys and the values will be assigned by the user.

We want a new column to be added to the dataframe where the values of this new column will be the values of the dictionary we have created with the mapping of indexes.

Mapping dataframe index using dictionary

For this purpose, we will first create a data frame then we will simply create another dictionary where the keys will be the indexes and we will define our values. For adding a new column, we will use the pandas.Index.to_series() method first so that all the indexes become the series and we will apply the map of function which will combine all the values of the dictionary with the indexes so that all the values will be assigned with the corresponding index in the data frame.

Let us understand with the help of an example,

Python program to map dataframe index using dictionary

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# Creating a DataFrame
df = pd.DataFrame({'one': {'A': 10, 'B': 20, 'C': 30, 'D': 40, 'E': 50}})

# Display Original df
print("Original DataFrame:\n",df,"\n")

# Creating a dictionary
d = {{'A': 'Hello', 'B': 'World', 'C': 'How', 'D': 'are', 'E': 'you?'}}

# Creating new column
df['New'] = df.index.to_series().map(d)

# Display result
print("Result:\n",df)

Output

The output of the above program is:

Example: Map dataframe index using dictionary

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.