Removing Duplicates

Python · Data Cleaning

Theory

df.drop_duplicates() removes the rows that duplicated() would flag and returns the rest. With no arguments it removes exact copies of whole rows. subset=['customer_id'] keeps one row per key even if other columns differ, and keep='first', 'last' or False chooses which copy survives (False removes every copy of a repeated key). ignore_index=True renumbers the result 0, 1, 2.

The most common real task is 'keep the latest record per key'. Because drop_duplicates keeps rows by position, sort first: df.sort_values('updated_at').drop_duplicates('customer_id', keep='last') keeps each customer's newest row. This is the pandas version of SQL's ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY updated_at DESC) = 1. An alternative is df.loc[df.groupby('customer_id')['updated_at'].idxmax()]. Just to remove duplicates in one column of values, use s.drop_duplicates() or s.unique().

Why we use it

Feeds and exports often send the same record more than once, or send updates as new rows. Removing the extra copies, and choosing the right one to keep, gives one trustworthy row per entity.

When to use it

Use drop_duplicates() for exact copies, subset= for one row per business key, and sort + keep='last' for the latest version. If duplicates should be combined (summed or averaged) rather than dropped, use groupby instead.

How it works

  1. Duplicate keys found
  2. Are they exact copies of the whole row? Yes: df.drop_duplicates(). No: Decide which version wins.
  3. Sort by the column that decides the winner, e.g. updated_at
  4. drop_duplicates(subset=key, keep='last')
  5. Check: df[key].is_unique is True
  6. One row per key

Syntax

df.drop_duplicates(subset=None, keep='first' | 'last' | False, ignore_index=False)
df.sort_values('ts').drop_duplicates('key', keep='last')

Example

latest = (df.sort_values('updated_at')
            .drop_duplicates('customer_id', keep='last'))

Key points

Python topics

Getting Started

Variables & Data Types

Operators

Strings

Lists

Tuples

Sets

Dictionaries

Control Flow

Loops

Functions & OOP

Working with Data

Tooling & Errors

File Handling

Exception Handling

NumPy Library

Pandas Basics

Data Cleaning

Combining DataFrames (SQL Joins & Unions)

GroupBy & SQL-Style Analytics

Reshaping & Workflow

Data Visualization

Machine Learning (Scikit-Learn)

Advanced Python & AI

T
Tech Town
Log InSign Up Free
Home SQL Python DSA Power BI Snowflake Databricks Spark Gen AI Practice Problems Contest Blog

Python for Data Analysts

From basics to business insights — the complete step-by-step Python roadmap. Click any topic in the sidebar to open it right here.

{{ sectionCount }}
Sections
{{ topicCount }}
Topics
Free
Forever
Hands-on practice Practice Python Online 141 Python questions for data analysts — strings, records, dates, statistics and regex — with hidden tests and instant verdicts. Start practising →
Section {{ sec.num }}

{{ sec.label }}

Python  /  {{ current.sectionLabel }}  /  {{ current.name }}

{{ current.name }}

Theory

{{ current.def }}

Why we use it

{{ rich.why }}

When to use it

{{ rich.when }}

Diagram

{{ rich.dg.caption }}

{{ tb.title }}
{{ c.v }}
{{ rich.dg.op }}
➜
{{ rich.dg.output.title }}
{{ c.v }}
{{ nd.label }}
{{ nd.sub }}
{{ nd.label }}
{{ nd.sub }}
{{ rich.dg.left.title }}
{{ it }}
{{ rich.dg.right.title }}
{{ it }}
Flowchart — how it works
{{ nd.text }}
{{ nd.text }}
◇ {{ nd.text }}
Yes → {{ nd.yes }}
No → {{ nd.no }}
Syntax
{{ current.syntax }}
Example
{{ current.example }}
▶ Try It Live — runs real Python 3.12 in your browser (first run loads the engine)
{{ liveOutput }}
{{ liveError }}
Key Points — click to check off as you learn
  • {{ pt.mark }} {{ pt.text }}

Share this topic