Categories
Python Answers

How to replace values in a Python Pandas series via dictionary efficiently?

Spread the love

To replace values in a Python Pandas series via dictionary efficiently, we call replace with a dictionary.

For instance, we write

import pandas as pd, numpy as np

df = pd.DataFrame({'A': np.random.randint(0, 1000, 1000000)})
lst = df['A'].values.tolist()
d = {i: i+1 for i in range(1000)}
df['A'].map(d) 

to call values.tolist to convert the values in column A in the df data frame to a list.

Then we create a new dictionary d by setting i to i + 1 and returning them.

And then we call df['A'].map with d to map all the values with d by returning a value 1 bigger than the current one.

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 *