Sometimes data has empty spots called missing values. Filling them helps us keep the data complete and ready for analysis.
Filling missing values (fillna) in 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.
df.fillna(0)df.fillna({'Age': 30, 'Name': 'Unknown'})df.fillna(method='ffill')df.fillna(method='bfill', limit=1)
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.
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)
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.
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.
Practice
fillna() function do in a pandas DataFrame?Solution
Step 1: Understand the purpose of fillna()
Thefillna()function is designed to handle missing data by replacing NaN values.Step 2: Identify what fillna() replaces missing values with
It can replace missing values with a fixed value or use methods like forward fill or backward fill.Final Answer:
It replaces missing values with a specified value or method. -> Option BQuick Check:
fillna() replaces NaN values = D [OK]
- Confusing fillna() with dropna() which deletes rows
- Thinking fillna() sorts data
- Assuming fillna() changes data types
df?Solution
Step 1: Identify the correct method call on a DataFrame column
To fill missing values in a specific column, callfillna()on that column likedf['Age'].fillna(30).Step 2: Check syntax correctness
df['Age'].fillna(30) uses correct syntax: column selection with brackets and method call with parentheses and argument.Final Answer:
df['Age'].fillna(30) -> Option DQuick Check:
Correct method call syntax = A [OK]
- Using square brackets instead of parentheses for fillna()
- Calling fillna on DataFrame with wrong syntax
- Using fill() instead of fillna()
df below, what will be the output of df['Score'].fillna(0)?
import pandas as pd
df = pd.DataFrame({'Score': [10, None, 20, None, 30]})
print(df['Score'].fillna(0))Solution
Step 1: Understand fillna(0) effect on NaN values
Callingfillna(0)replaces all missing (NaN) values with 0.Step 2: Apply fillna(0) to the 'Score' column
The original column has values [10, NaN, 20, NaN, 30]. After fillna(0), NaNs become 0, so result is [10, 0, 20, 0, 30].Final Answer:
[10, 0, 20, 0, 30] -> Option CQuick Check:
NaN replaced by 0 = C [OK]
- Expecting fillna() to remove rows
- Thinking fillna() copies previous values by default
- Confusing fillna(0) with fillna(method='ffill')
df?
df.fillna(method='forward')
Solution
Step 1: Check valid method names for fillna()
fillna() supports method='ffill' for forward fill and method='bfill' for backward fill.Step 2: Identify the incorrect method name
The code uses method='forward', which is invalid. The correct name is 'ffill'.Final Answer:
The method name should be 'ffill', not 'forward'. -> Option AQuick Check:
Correct method name = 'ffill' [OK]
- Using 'forward' instead of 'ffill'
- Thinking fillna() can't use methods
- Calling fillna() only on columns, not DataFrame
df with missing values in multiple columns. You want to fill missing values in column 'A' with the mean of 'A', and in column 'B' with the previous valid value. Which code correctly does this?Solution
Step 1: Fill column 'A' with its mean
Calculate mean withdf['A'].mean()and fill missing values usingfillna()on column 'A'. Assign back todf['A'].Step 2: Fill column 'B' with previous valid value
Usefillna(method='ffill')on column 'B' to forward fill missing values. Assign back todf['B'].Final Answer:
df['A'] = df['A'].fillna(df['A'].mean()) df['B'] = df['B'].fillna(method='ffill') -> Option AQuick Check:
Mean fill + forward fill = B [OK]
- Using fillna() without assignment, so no change saved
- Passing 'ffill' as string value instead of method argument
- Trying to use method='mean' which is invalid
Ready to prove it?
Pass the test and this pattern moves unknown
