Table of Contents
In order to replace inf values with zeros in Pandas, one can use the replace() method of the DataFrame or the Series class. We can pass the inf value as an argument to the to_replace parameter and set the value parameter to 0. This will replace all the inf values with 0s in the dataframe or series. It is important to note that this operation takes place in-place, meaning that the dataframe or series will be modified directly without returning a new object.
You can use the following syntax to replace inf and -inf values with zero in a pandas DataFrame:
df.replace([np.inf, -np.inf], 0, inplace=True)
The following example shows how to use this syntax in practice.
Example: Replace inf with Zero in Pandas
Suppose we have the following pandas DataFrame that contains information about various basketball players:
import pandas as pd import numpy as np #create DataFrame df = pd.DataFrame({'team': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'], 'points': [18, np.inf, 19, np.inf, 14, 11, 20, 28], 'assists': [5, 7, 7, 9, 12, 9, 9, np.inf], 'rebounds': [np.inf, 8, 10, 6, 6, -np.inf, 9, 12]}) #view DataFrame df team points assists rebounds 0 A 18.0 5.0 inf 1 B inf 7.0 8.0 2 C 19.0 7.0 10.0 3 D inf 9.0 6.0 4 E 14.0 12.0 6.0 5 F 11.0 9.0 -inf 6 G 20.0 9.0 9.0 7 H 28.0 inf 12.0
Notice that there are several inf and -inf values throughout the DataFrame.
We can use the following syntax to replace these inf and -inf values with zero:
#replace inf and -inf with zero
df.replace([np.inf, -np.inf], 0, inplace=True)
#view updated DataFrame
df
team points assists rebounds
0 A 18.0 5.0 0.0
1 B 0.0 7.0 8.0
2 C 19.0 7.0 10.0
3 D 0.0 9.0 6.0
4 E 14.0 12.0 6.0
5 F 11.0 9.0 0.0
6 G 20.0 9.0 9.0
7 H 28.0 0.0 12.0
Notice that each of the inf and -inf values have been replaced with zero.
Note: You can find the complete documentation for the replace function in pandas .