Home > Software engineering >  Replacing values in entire dataframe based on dictionary
Replacing values in entire dataframe based on dictionary

Time:02-13

I have a large dataframe in which I want to change every value based on a dictionary. Currently I am using a loop:

for column in df.columns:
     df = df.replace({column: dictionary})

This works but it is pretty slow. This single for loop takes around 90% of the time that it takes my entire code to run. Is there a faster method using loc, map or replace?

There are lots of other questions like this already but it seems pretty much everyone else is just trying to change individual columns rather than the entire dataframe.

I'm using Spyder with Python 3.9 on Windows. Thanks!

Edit: I found a way to make it faster by switching rows and columns. Previously I had lots of columns and few rows, now that it's the other way around the code is a lot faster. Still, is there a way to replace values in the entire dataframe rather than just individual columns?

CodePudding user response:

Is there a way to replace values in the entire dataframe rather than just individual columns?

Use:

df = df.replace(dictionary)
  • Related