⊕
⊖
Contents
Pandas DataFrame – Replace Multiple Values
To replace multiple values in a DataFrame, you can use DataFrame.replace() method with a dictionary of different replacements passed as argument.
Examples
1. Replace multiple values in a column
The syntax to replace multiple values in a column of DataFrame is
DataFrame.replace({'column_name' : { old_value_1 : new_value_1, old_value_2 : new_value_2}})
In the following example, we will use replace() method to replace 1 with 11 and 2 with 22 in column a.
Python Program
import pandas as pd
df = pd.DataFrame([
[4, -9, 8],
[1, 2, -4],
[2, 2, -8],
[0, 7, -4],
[2, 5, 1]],
columns=['a', 'b', 'c'])
df = df.replace({'a':{1:11, 2:22}})
print(df)
Run Code CopyOutput
a b c
0 4 -9 8
1 11 2 -4
2 22 2 -8
3 0 7 -4
4 22 5 1
2. Replace multiple values in multiple columns
The syntax to replace multiple values in multiple columns of DataFrame is
DataFrame.replace({'column_name_1' : { old_value_1 : new_value_1, old_value_2 : new_value_2},
'column_name_2' : { old_value_1 : new_value_1, old_value_2 : new_value_2}})
In the following example, we will use replace() method to replace 1 with 11 and 2 with 22 in column a; 5 with 55 and 2 with 22 in column b.
Python Program
import pandas as pd
df = pd.DataFrame([
[4, -9, 8],
[1, 2, -4],
[2, 2, -8],
[0, 7, -4],
[2, 5, 1]],
columns=['a', 'b', 'c'])
df = df.replace({'a':{1:11, 2:22}, 'b':{5:55, 2:22}})
print(df)
Run Code CopyOutput
a b c
0 4 -9 8
1 11 22 -4
2 22 22 -8
3 0 7 -4
4 22 55 1
Summary
In this tutorial of Python Examples, we learned how to replace multiple values in Pandas DataFrame in one or more columns.