How to Replace Values in a pandas DataFrame

In this tutorial, you will learn how to replace values in a DataFrame.

TLDR solution

# replace one specific value in a column
df['column_a'] = df['column_a'].replace("x", "y")

# replace multiple values (x, y) with one value (z) in a column
df['column_a'] = df['column_a'].replace(["x", "y"], "z")

# replace values (w, x) with other values (y, z) in a column
df['column_a'] = df['column_a'].replace(["w", "x"], ["y", "z"])

# replace one specific value in the entire df
df = df.replace("x", "y")

Examples

Let's say, you have the following DataFrame:

df
       a      b
0  fish1    eel
1  fish2    cod
2  shark  fish1

Example 1: Replace one Specific Value in a Column

df['a'] = df['a'].replace("fish1", "salmon")

Now the DataFrame looks like this:

df
        a      b
0  salmon    eel
1   fish2    cod
2   shark  fish1

Example 2: Replace Multiple Values With one Value in a Column

df['a'] = df['a'].replace(["fish1", "fish2"], "salmon")

Result:

df
        a      b
0  salmon    eel
1  salmon    cod
2   shark  fish1

Example 3: Replace Multiple Values With Mapped Values in a Column

df['a'] = df['a'].replace(["fish1", "fish2"], ["salmon", "pufferfish"])

Result:

df
            a      b
0      salmon    eel
1  pufferfish    cod
2       shark  fish1

Example 4: Replace one Specific Value in the Entire DataFrame

df = df.replace("fish1", "salmon")

Now the DataFrame looks like this:

Result:

df
        a       b
0  salmon     eel
1   fish2     cod
2   shark  salmon

Bonus Example: Replace a Substring in a Column

df['a'] = df['a'].str.replace("fish", "thing")

Result:

df
        a       b
0  thing1     eel
1  thing2     cod
2   shark   fish1

That's it! You just learned how to replace values in a pandas DataFrame.