Pandas: How to Replace Multiple Values in One Column


You can use the following basic syntax to replace multiple values in one column of a pandas DataFrame:

df = df.replace({'my_column' : {'old1' : 'new1', 'old2' : 'new2', 'old3' : 'new3'}})

The following example shows how to use this syntax in practice.

Example: Replace Multiple Values in One Column in Pandas

Suppose we have the following pandas DataFrame that contains information about various basketball players:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'position': ['G', 'G', 'F', 'F', 'F', 'C', 'C'],
                   'points': [28, 17, 19, 14, 23, 26, 5],
                   'rebounds': [5, 6, 4, 7, 14, 12, 9],
                   'assists': [10, 13, 7, 8, 4, 5, 8]})

#view DataFrame
print(df)

  position  points  rebounds  assists
0        G      28         5       10
1        G      17         6       13
2        F      19         4        7
3        F      14         7        8
4        F      23        14        4
5        C      26        12        5
6        C       5         9        8

Suppose we would like to make the following replacements in the position column:

  • Replace ‘G’ with ‘Guard’
  • Replace ‘F’ with ‘Forward’
  • Replace C with ‘Center’

We can use the following syntax to do so:

#replace multiple values in position column
df = df.replace({'position' : {'G' : 'Guard', 'F' : 'Forward', 'C' : 'Center'}})

#view updated DataFrame
print(df)

  position  points  rebounds  assists
0    Guard      28         5       10
1    Guard      17         6       13
2  Forward      19         4        7
3  Forward      14         7        8
4  Forward      23        14        4
5   Center      26        12        5
6   Center       5         9        8

Notice that multiple values have been replaced in the position column.

We can use similar syntax to replace multiple values in a numeric column.

For example, the following code shows how to make the following replacements in the assists column:

  • Replace 10 with 20
  • Replace 13 with 15
  • Replace 8 with 10

We can use the following syntax to do so:

#replace multiple values in assists column
df = df.replace({'assists' : {10:20, 13:15, 8:10}})

#view updated DataFrame
print(df)

  position  points  rebounds  assists
0        G      28         5       20
1        G      17         6       15
2        F      19         4        7
3        F      14         7       10
4        F      23        14        4
5        C      26        12        5
6        C       5         9       10

Notice that multiple values have been replaced in the assists column.

Additional Resources

The following tutorials explain how to perform other common tasks in pandas:

How to Replace NaN Values with Zeros in Pandas
How to Replace Empty Strings with NaN in Pandas
How to Replace Values in Column Based on Condition in Pandas

Leave a Reply

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