4 C
London
Friday, December 20, 2024
HomePandas in PythonDataFrame Functions in PythonPandas: How to Replace Zero with NaN

Pandas: How to Replace Zero with NaN

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

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

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories