How to replace NaN values by Zeroes in a column of a Pandas DataFrame?

PandasServer Side ProgrammingProgramming

To replace NaN values by zeroes or other values in a column of a Pandas DataFrame, we can use df.fillna() method.

Steps

  • Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df.

  • Print the input DataFrame, df.

  • Use df.fillna(0) to replace NaN in DataFrame with value 0.

  • Similarly use df.fillna(5) and df.fillna(7) to replace NaN in DataFrame with 5 and 7, respectively.

  • Print the replaced NaN, DataFrame.

Example

 Live Demo

import pandas as pd
import numpy as np

df = pd.DataFrame(
   {
      "x": [5, np.nan, 1, np.nan],
      "y": [np.nan, 1, np.nan, 10],
      "z": [np.nan, 1, np.nan, np.nan]
   }
)
print "Input series is:\n", df
print "After replacing NaN with 0:\n", df.fillna(0)
print "After replacing NaN with 5:\n", df.fillna(5)
print "After replacing NaN with 7:\n", df.fillna(7)

Output

Input series is:
    x  y    z
0 5.0  NaN  NaN
1 NaN  1.0  1.0
2 1.0  NaN  NaN
3 NaN  10.0 NaN

After replacing NaN with 0:
    x   y    z
0 5.0   0.0  0.0
1 0.0   1.0  1.0
2 1.0   0.0  0.0
3 0.0  10.0  0.0

After replacing NaN with 5:
   x    y    z
0 5.0  5.0   5.0
1 5.0  1.0   1.0
2 1.0  5.0   5.0
3 5.0  10.0  5.0

After replacing NaN with 7:
    x    y     z
0  5.0  7.0   7.0
1  7.0  1.0   1.0
2  1.0  7.0   7.0
3  7.0  10.0  7.0
raja
Published on 30-Aug-2021 12:01:58
Advertisements