2

How would you use a dictionary to replace values throughout all the columns in a dataframe?

Below is an example, where I attempted to pass the dictionary through the replace function. I have a script that produces various sized dataframes based on a company's manager/employee structure - so the number of columns varies per dataframe.

import pandas as pd
import numpy as np

df = pd.DataFrame({'col2': {0: 'a', 1: 2, 2: np.nan}, 'col1': {0: 'w', 1: 1, 2: 2}, 'col3': {0: 'w', 1: 1, 2: 2}, 'col4': {0: 'w', 1: 1, 2: 2}})
di = {1: "A", 2: "B"}
print(df)

df = df.replace({di})
print(df)

There is a similar question linked below in which the solution specifies column names, but given that I'm looking at a whole dataframe that would vary in column names/size, I'd like to apply the replace function to the whole dataframe.

Remap values in pandas column with a dict

Thanks!

U13-Forward
  • 69,221
  • 14
  • 89
  • 114

1 Answers1

1

Don't put {} around your dictionary - that tries to turn it into a set, which throws an error since a dictionary can't be an element in a set. Instead pass in the dictionary directly:

import pandas as pd
import numpy as np

df = pd.DataFrame({'col2': {0: 'a', 1: 2, 2: np.nan}, 'col1': {0: 'w', 1: 1, 2: 2}, 'col3': {0: 'w', 1: 1, 2: 2}, 'col4': {0: 'w', 1: 1, 2: 2}})
di = {1: "A", 2: "B"}
print(df)

df = df.replace(di)
print(df)

Output:

  col1 col2 col3 col4
0    w    a    w    w
1    1    2    1    1
2    2  NaN    2    2
  col1 col2 col3 col4
0    w    a    w    w
1    A    B    A    A
2    B  NaN    B    B
Primusa
  • 13,136
  • 3
  • 33
  • 53