fill nans with zeros in python

If you want to fill NaN values with zeros in Python using pandas, you can use the fillna() function.

Here is an example of how to fill NaN values with zeros in a DataFrame:

main.py
import pandas as pd

# Create a DataFrame with NaN values
df = pd.DataFrame({'A': [1, 2, None, 4, 5],
                   'B': [None, 2, 3, None, 5]})

# Fill NaN values with zeros
df = df.fillna(0)

print(df)
209 chars
11 lines

Output:

main.py
     A    B
0  1.0  0.0
1  2.0  2.0
2  0.0  3.0
3  4.0  0.0
4  5.0  5.0
72 chars
7 lines

In this example, we first create a DataFrame with NaN values. Then, we use the fillna() function and pass 0 as the argument to fill all NaN values in the DataFrame with zeros.

Note that the original DataFrame df is modified in-place. If you want to create a new DataFrame without modifying the original one, you can use the fillna() function with the inplace=False parameter:

main.py
new_df = df.fillna(0, inplace=False)
37 chars
2 lines

I hope this helps!

related categories

gistlibby LogSnag