change nan in dataframe to zero in python

To change the NaN values in a dataframe to zero, you can use the fillna() method in pandas. Here's an example of how to do it:

main.py
import pandas as pd

# Create a sample dataframe
df = pd.DataFrame({'A': [1, 2, np.nan, 4],
                   'B': [5, np.nan, 7, 8],
                   'C': [np.nan, 10, 11, 12]})

# Print the original dataframe
print("Original Dataframe:")
print(df)

# Fill the NaN values with zero
df.fillna(0, inplace=True)

# Print the modified dataframe
print("\nDataframe after replacing NaN with zero:")
print(df)
407 chars
18 lines

This will replace all NaN values in the dataframe df with zero. The fillna() method allows you to specify the value to replace NaN with. Using inplace=True ensures that the modification is done directly on the dataframe object.

related categories

gistlibby LogSnag