Replace NaN Values with Zeros in Pandas DataFrame

Replace NaN Values with Zeros in Pandas DataFrame

In the pandas library, you can easily replace NaN (Not a Number) values with zeros (or any other value) in a DataFrame using the fillna() method.

Here's how you can replace NaN values with zeros in a Pandas DataFrame:

import pandas as pd import numpy as np # Sample DataFrame with NaN values data = { 'A': [1, 2, np.nan], 'B': [4, np.nan, 6], 'C': [7, 8, 9] } df = pd.DataFrame(data) print("Original DataFrame:") print(df) # Replacing NaN values with zeros df.fillna(0, inplace=True) print("\nDataFrame after replacing NaN with 0:") print(df) 

Output:

Original DataFrame: A B C 0 1.0 4.0 7 1 2.0 NaN 8 2 NaN 6.0 9 DataFrame after replacing NaN with 0: A B C 0 1.0 4.0 7 1 2.0 0.0 8 2 0.0 6.0 9 

In the above example, the fillna() method replaces all NaN values in the DataFrame with zeros. The inplace=True argument ensures that the change is made directly to the original DataFrame without having to reassign it. If you prefer to create a new DataFrame without altering the original one, you can omit the inplace argument and assign the result to a new variable.


More Tags

custom-data-attribute ssrs-expression viewdidappear iokit circular-dependency playsound vaadin mtu sqoop remote-debugging

More Programming Guides

Other Guides

More Programming Examples