clean the data by filling nan in python

To fill NaN values in a Pandas DataFrame in Python, you can use the fillna method.

Here's an example code:

main.py
import pandas as pd

# create a sample DataFrame
df = pd.DataFrame({
   'name': ['John', 'Sara', 'Alice', 'Peter'],
   'age': [30, 24, None, 35],
   'gender': ['M', None, 'F', 'M']
})

# print the original DataFrame
print("Original DataFrame:")
print(df)

# fill NaN values with zeros
df.fillna(0, inplace=True)

# print the cleaned DataFrame
print("Cleaned DataFrame:")
print(df)
381 chars
20 lines

In this example, NaN values are filled with zeros using the fillna method with the inplace=True parameter to modify the DataFrame in place.

You can fill NaN values with any other value or method of your choice, including the previous value, the mean, or the median.

related categories

gistlibby LogSnag