0
0
Data Analysis Pythondata~5 mins

Filling missing values (fillna) in Data Analysis Python

Choose your learning style9 modes available
Introduction

Sometimes data has empty spots called missing values. Filling them helps us keep the data complete and ready for analysis.

You have a table with some empty cells and want to replace them with a number or word.
You want to fill missing dates in a timeline with the last known value.
You need to prepare data for a machine learning model that can't handle empty values.
You want to replace missing survey answers with a default response.
Syntax
Data Analysis Python
DataFrame.fillna(value=None, method=None, inplace=False, limit=None)

value: The value to replace missing spots with (like 0 or 'unknown').

method: Use 'ffill' to fill forward or 'bfill' to fill backward from nearby values.

Examples
Replace all missing values with zero.
Data Analysis Python
df.fillna(0)
Fill missing 'Age' with 30 and missing 'Name' with 'Unknown'.
Data Analysis Python
df.fillna({'Age': 30, 'Name': 'Unknown'})
Fill missing values by copying the previous row's value down.
Data Analysis Python
df.fillna(method='ffill')
Fill missing values by copying the next row's value up, but only for one missing spot in a row.
Data Analysis Python
df.fillna(method='bfill', limit=1)
Sample Program

This code creates a table with some missing spots. It fills missing ages with 0, missing names with 'Unknown', and fills missing cities by copying the previous city down.

Data Analysis Python
import pandas as pd

# Create a simple table with missing values
 data = {'Name': ['Alice', None, 'Charlie', 'David'],
         'Age': [25, None, 30, None],
         'City': ['New York', 'Los Angeles', None, 'Chicago']}

df = pd.DataFrame(data)

print('Original DataFrame:')
print(df)

# Fill missing values: Age with 0, Name with 'Unknown', City forward fill
filled_df = df.fillna({'Age': 0, 'Name': 'Unknown'}).fillna(method='ffill')

print('\nDataFrame after filling missing values:')
print(filled_df)
OutputSuccess
Important Notes

Using inplace=True changes the original table directly without making a new one.

Filling missing values helps avoid errors in calculations or models that don't accept empty spots.

Summary

Missing values can be filled with a fixed value or by copying nearby values.

Use fillna() to replace missing spots in your data.

Filling missing data keeps your analysis smooth and error-free.