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/Develop a Python script to clean data by removing duplicates and handling missing values.

Develop a Python script to clean data by removing duplicates and handling missing values.

Python/Codingeasy2 min read

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

To clean data in Python, primarily use the Pandas library. The script will involve identifying and removing duplicate rows using df.drop duplicates() and handling missing values through df.dropna() or…

🤖 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
Fragma Data Systems
Key Concepts Tested
python

Why This Question Matters

This easy-level Python/Coding question appears frequently in data engineering interviews at companies like Fragma Data Systems. While less common, it tests deeper understanding that distinguishes strong candidates. Mastering the underlying concepts (python) will help you answer variations of this question confidently.

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
398 wordsIncludes code

To clean data in Python, primarily use the Pandas library. The script will involve identifying and removing duplicate rows using df.drop_duplicates() and handling missing values through df.dropna() or df.fillna() with appropriate imputation strategies.

Core Cleaning Mechanics

Removing Duplicates:
Use df.drop_duplicates(subset=['col1', 'col2'], keep='first'). The subset parameter specifies columns to consider for uniqueness, and keep determines which duplicate (first, last, or False to drop all) to retain. This ensures data integrity and prevents skewed aggregations or analyses in downstream processes.

Handling Missing Values:
* df.dropna(subset=['col'], how='any') removes rows or columns containing NaN values. While simple, it can lead to significant data loss, especially with sparse datasets.
* df.fillna(value) replaces NaN with a specified constant.
* df.fillna(method='ffill') or df.fillna(method='bfill') propagates the last/next valid observation forward/backward.
* df.fillna({'col_a': df['col_a'].median(), 'col_b': df['col_b'].mode()[0]}) allows for column-specific imputation, often using statistical measures like median for numerical data or mode for categorical data.
The choice depends on the data distribution and domain knowledge, aiming to preserve sample size and avoid introducing bias.

Outlier Detection (Optional but Recommended):
While not explicitly asked, identifying outliers is crucial for robust data. A common statistical approach is df[(df['col'] - df['col'].mean()).abs() < 3 * df['col'].std()], which filters data points within three standard deviations of the mean. Outliers might be removed, capped, or transformed depending on their nature and impact.

Here's a concise example:

import pandas as pd
import numpy as np

data = {'id': [1, 2, 2, 3], 'value': [10, np.nan, 20, 30], 'category': ['A', 'B', 'B', 'C']}
df = pd.DataFrame(data)

# Remove duplicates based on 'id' and 'category'
df_cleaned = df.drop_duplicates(subset=['id', 'category'], keep='first')

# Impute missing 'value' with the median
median_value = df_cleaned['value'].median()
df_cleaned['value'] = df_cleaned['value'].fillna(median_value)

# print(df_cleaned)


Choosing between dropna() and fillna() involves a trade-off between data loss and potential imputation bias. Simple imputation methods (mean/median) are quick but might not capture complex relationships, whereas advanced methods (e.g., regression imputation) are more accurate but computationally intensive. For very large datasets, Pandas might be insufficient, necessitating distributed frameworks like PySpark, where drop_duplicates can trigger expensive data shuffles across partitions.

In the interview, also mention documenting all cleaning decisions for reproducibility and auditability. In a production environment, integrate schema validation (e.g., using Great Expectations or Pydantic) to ensure data quality pre- and post-cleaning, and log statistics on removed duplicates or imputed values. This process often forms a critical step within a dbt model or a Spark transformation job.

⚡
Pro Tip

Pro-Move: Document + validate. Red Flag: Silent drop without logging.

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