Essential cookies keep authentication working. With your permission, we also use analytics cookies to understand and improve the product. Read our Privacy Policy

DataEngPrep.tech
QuestionsPracticeAI CoachDashboardPricingBlog
ProLogin
Home/Questions/Python/Coding/How do you clean missing values in a pandas DataFrame?

How do you clean missing values in a pandas DataFrame?

Python/Codingeasy2 min read

Reviewed by Aditya Kumar · Last reviewed 2026-03-24

To clean missing values in a pandas DataFrame, the primary methods are df.dropna() for removing rows or columns, and df.fillna() for imputing values. The choice depends on the nature of the…

🤖 Analyze Your Answer
Frequency
Low
Asked at 1 company
Category
179
questions in Python/Coding
Difficulty Split
127E|24M|28H
in this category
Total Bank
1,863
across 7 categories
Asked at these companies
Swiggy

Why This Question Matters

This easy-level Python/Coding question appears frequently in data engineering interviews at companies like Swiggy. While less common, it tests deeper understanding that distinguishes strong candidates.

How to Approach This

Start by clearly defining the core concept being asked about. Interviewers want to see that you understand the fundamentals before diving into implementation details. Structure your answer with a definition, then explain the practical application with a concise example. The expert answer includes a code example that demonstrates the implementation pattern.

Expert Answer
425 wordsIncludes code

To clean missing values in a pandas DataFrame, the primary methods are df.dropna() for removing rows or columns, and df.fillna() for imputing values. The choice depends on the nature of the missingness, the data type, and the impact on downstream analysis.

Mechanics and Why

Before cleaning, it's crucial to identify missing values using df.isna() or df.isnull() and understand their distribution (df.isnull().sum()).

* df.dropna(): This method removes rows or columns containing missing values. Parameters like how='any' (default) or how='all' and thresh (minimum non-null values required) provide control over the removal criteria. Use dropna() when the amount of missing data is small, or when the missingness is truly random and dropping won't introduce significant bias or data loss.
* df.fillna(): This method imputes missing values. Common strategies include:
* Statistical Imputation: For numerical columns, fillna(df['column'].mean()) or fillna(df['column'].median()) are common to preserve central tendency. For categorical columns, fillna(df['column'].mode()[0]) uses the most frequent category.
* Forward/Backward Fill: ffill() (forward fill) or bfill() (backward fill) are effective for time-series or ordered data, propagating the last known valid observation.
* Constant Value: fillna(0) or another specific value can be used when a default or placeholder is appropriate.
* Per-Column Strategy: It's often best to apply different fillna() strategies per column based on data type and domain knowledge.

Documenting the chosen cleaning strategy is vital for data governance and reproducibility, especially in production pipelines (e.g., within dbt models) to ensure data lineage and consistency.

Key Trade-offs and Production Considerations

While dropna() is simple, it can lead to significant data loss and introduce bias if missingness is not completely random. Imputation with fillna() can preserve more data but risks distorting the original data distribution or introducing artificial patterns.

In production, it's critical to validate that imputation doesn't bias downstream models or analytics. This involves comparing key statistics (mean, median, standard deviation) and distributions (histograms) before and after imputation. For example, in a Spark or Snowflake environment, these data quality checks would be integrated into ETL/ELT stages before data is consumed.

import pandas as pd
import numpy as np

df = pd.DataFrame({
'A': [1, 2, np.nan, 4],
'B': [np.nan, 6, 7, 8],
'C': ['X', 'Y', 'X', np.nan]
})

# Impute 'A' with median, 'B' with mean, 'C' with mode
df['A'] = df['A'].fillna(df['A'].median())
df['B'] = df['B'].fillna(df['B'].mean())
df['C'] = df['C'].fillna(df['C'].mode()[0])

In the interview, also mention: The importance of understanding the mechanism of missing data (Missing Completely At Random - MCAR, Missing At Random - MAR, Missing Not At Random - MNAR) as this informs the most appropriate cleaning strategy and potential biases.

⚡
Pro Tip

Pro-Move: Per-column strategy. Red Flag: Blind fillna(0).

Want all answers as a PDF for offline study?
Seven focused volumes with 750+ in-depth answers — Answer Vault →

Related Python/Coding Questions

easyWhat are traits in Scala, and how are they different from classes?FreemediumWrite a Python function to check if a string is a palindrome.FreeeasyWhat is the difference between a list and a tuple in Python?FreeeasyExplain the difference between shallow copy and deep copy in Python.FreeeasyWrite a Python function to find the first non-repeating character in a string.Free

Level up your prep

Recommended
Educative
Educative Unlimited

800+ hands-on courses — Grokking System Design, Coding Patterns, and AI mock interviews for your DE loop.

Start learning →

Some links below are affiliate links. If you buy through them we may earn a small commission at no extra cost to you — it helps keep DataEngPrep free.

According to DataEngPrep.tech, this is one of the most frequently asked Python/Coding interview questions, reported at 1 company. DataEngPrep.tech maintains an editor-reviewed database of 1,863 data engineering interview questions across 7 categories.

← Back to all questionsMore Python/Coding questions →
Categories
All QuestionsSQLSpark / Big DataPython / CodingSystem DesignCloud / ToolsBehavioral
By Company
AmazonGoogleDatabricksSnowflakeAWSAzureMicrosoftNetflixUberTCS
Interview Guides
All GuidesTop SQL QuestionsTop Spark QuestionsPySpark QuestionsTop Python QuestionsTop System DesignKafka QuestionsAirflow QuestionsSQL Window FunctionsETL QuestionsData Modeling
Products
AI Interview CoachAnswer AnalyzerSQL PlaygroundResume AnalyzerAnswer Vault PDFsPricing
Company
About & Editorial PolicyContact UsAI DisclosureDisclaimerTerms of ServicePrivacy Policy
© 2026 DataEngPrep.tech. All rights reserved.
AboutBlogContactDisclaimer