You can use the following basic syntax to replace zeros with NaN values in a pandas DataFrame:
df.replace(0, np.nan, inplace=True)
The following example shows how to use this syntax in practice.
Example: Replace Zero with NaN in Pandas
Suppose we have the following pandas DataFrame:
import pandas as pd
#create DataFrame
df = pd.DataFrame({'points': [25, 0, 15, 14, 19, 23, 25, 29],
'assists': [5, 0, 7, 0, 12, 9, 9, 4],
'rebounds': [11, 8, 10, 6, 6, 0, 9, 0]})
#view DataFrame
print(df)
points assists rebounds
0 25 5 11
1 0 0 8
2 15 7 10
3 14 0 6
4 19 12 6
5 23 9 0
6 25 9 9
7 29 4 0
We can use the following syntax to replace each zero in the DataFrame with a NaN value:
import numpy as np
#replace all zeros with NaN values
df.replace(0, np.nan, inplace=True)
#view updated DataFrame
print(df)
points assists rebounds
0 25.0 5.0 11.0
1 NaN NaN 8.0
2 15.0 7.0 10.0
3 14.0 NaN 6.0
4 19.0 12.0 6.0
5 23.0 9.0 NaN
6 25.0 9.0 9.0
7 29.0 4.0 NaN
Notice that each zero in every column of the DataFrame has been replaced with NaN.
Note: We must use the argument inplace=True or else the changes won’t be made to the original DataFrame.
Related: How to Replace NaN Values with Zero in Pandas
Additional Resources
The following tutorials explain how to perform other common operations in pandas:
How to Replace Specific Values in Pandas
How to Filter a Pandas DataFrame by Column Values
How to Fill NA Values for Multiple Columns in Pandas