Often you may want to replace the values in one or more columns of a pandas DataFrame.
Fortunately this is easy to do using the .replace() function.
This tutorial provides several examples of how to use this function in practice on the following DataFrame:
import pandas as pd #create DataFrame df = pd.DataFrame({'team': ['A', 'A', 'B', 'B', 'B', 'C', 'C'], 'division':['E', 'W', 'E', 'E', 'W', 'W', 'E'], 'rebounds': [11, 8, 7, 6, 6, 5, 12]}) #view DataFrame print(df) team division rebounds 0 A E 11 1 A W 8 2 B E 7 3 B E 6 4 B W 6 5 C W 5 6 C E 12
Example 1: Replace a Single Value in an Entire DataFrame
The following code shows how to replace a single value in an entire pandas DataFrame:
#replace 'E' with 'East' df = df.replace(['E'],'East') #view DataFrame print(df) team division rebounds 0 A East 11 1 A W 8 2 B East 7 3 B East 6 4 B W 6 5 C W 5 6 C East 12
Example 2: Replace Multiple Values in an Entire DataFrame
The following code shows how to replace multiple values in an entire pandas DataFrame:
#replace 'E' with 'East' and 'W' with 'West' df = df.replace(['E', 'W'],['East', 'West']) #view DataFrame print(df) team division rebounds 0 A East 11 1 A West 8 2 B East 7 3 B East 6 4 B West 6 5 C West 5 6 C East 12
Example 3: Replace a Single Value in a Single Column
The following code shows how to replace a single value in a single column:
#replace 6 with 0 in rebounds column df['rebounds'] = df['rebounds'].replace(6, 0) #view DataFrame print(df) team division rebounds 0 A E 11 1 A W 8 2 B E 7 3 B E 0 4 B W 0 5 C W 5 6 C E 12
Example 4: Replace Multiple Values in a Single Column
The following code shows how to replace multiple values in a single column:
#replace 6, 11, and 8 with 0, 1 and 2 in rebounds column df['rebounds'] = df['rebounds'].replace([6, 11, 8], [0, 1, 2]) #view DataFrame print(df) team division rebounds 0 A E 1 1 A W 2 2 B E 7 3 B E 0 4 B W 0 5 C W 5 6 C E 12
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