Categories
Python Answers

How to add a new Python Pandas column with mapped value from a dictionary?

Spread the love

To add a new Python Pandas column with mapped value from a dictionary, we can call the map method.

For instance, we write

import pandas as pd

equiv = {7001:1, 8001:2, 9001:3}
df = pd.DataFrame( {"A": [7001, 8001, 9001]} )
df["B"] = df["A"].map(equiv)

to create the df dataframe.

Then we call map with a dictionary to map the values from the keys’ values to the values’ values.

And then we assign them to the B column.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *