0
0
Pandasdata~5 mins

Filling missing values with fillna() in Pandas

Choose your learning style9 modes available
Introduction

Sometimes data has empty spots called missing values. We use fillna() to fill these spots with useful values so our analysis works better.

You have a table of sales data with some missing numbers and want to replace them with zero.
You want to fill missing temperature readings with the average temperature.
You have survey data with some unanswered questions and want to fill them with a placeholder like 'Unknown'.
You want to replace missing dates in a timeline with the previous known date.
Syntax
Pandas
DataFrame.fillna(value=None, method=None, axis=None, inplace=False, limit=None)

value is what you want to fill the missing spots with.

method can fill forward or backward instead of a fixed value.

Examples
Fill all missing values with zero.
Pandas
df.fillna(0)
Fill missing values by copying the previous value downwards.
Pandas
df.fillna(method='ffill')
Fill missing values in 'Age' column with 30 and in 'Name' column with 'Unknown'.
Pandas
df.fillna({'Age': 30, 'Name': 'Unknown'})
Sample Program

This code creates a small table with missing values. Then it fills missing names with 'Unknown', missing ages with 30, and missing scores with 0.

Pandas
import pandas as pd

data = {'Name': ['Alice', 'Bob', None, 'David'],
        'Age': [25, None, 22, None],
        'Score': [85, 90, None, 88]}

df = pd.DataFrame(data)

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

# Fill missing values with specific values
filled_df = df.fillna({'Name': 'Unknown', 'Age': 30, 'Score': 0})

print('\nDataFrame after fillna():')
print(filled_df)
OutputSuccess
Important Notes

If you use inplace=True, the original DataFrame changes directly.

Using method='ffill' or method='bfill' fills missing values by copying nearby values.

Be careful to choose fill values that make sense for your data to avoid wrong conclusions.

Summary

fillna() helps replace missing data with values you choose.

You can fill with a fixed value, different values per column, or by copying nearby values.

Filling missing values makes your data cleaner and easier to analyze.