Pandas: How to Replace inf with Zero


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 here.

Additional Resources

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

How to Impute Missing Values in Pandas
How to Count Missing Values in Pandas
How to Fill NaN Values with Mean in Pandas

Leave a Reply

Your email address will not be published.