Removing Duplicate Rows in a CSV File Compared to Another CSV File

Abstract: Remove duplicate rows from a source CSV file by comparing it against a reference CSV using Python pandas.

Created: 2026-09-27 by
To remove duplicate rows from a CSV file by comparing it to another, you can use Python’s pandas library. By loading both files into DataFrames and using the merge function with an outer join on all columns, you can identify unique rows in each dataset. Filtering for rows that exist only in one of the DataFrames allows you to isolate and save the non-duplicate entries effectively.

Understanding the Problem

Data deduplication is a common requirement when merging datasets or cleaning imported data. Often, you have a primary dataset (let's call it source.csv) and a reference dataset (reference.csv). The goal is to keep only the rows in source.csv that do not appear in reference.csv, or vice versa, depending on your specific business logic. This process ensures that you are not processing redundant information, which can skew analytics or waste computational resources.

While Excel offers basic duplicate removal tools, it struggles with large files and complex comparison logic. Python provides a robust, scalable solution using the pandas library, which handles millions of rows efficiently and allows for precise control over how duplicates are identified and removed.

Prerequisites and Setup

Before writing the script, ensure you have Python installed on your system. You will also need the pandas library, which is the standard tool for data manipulation in Python. If you do not have it installed, you can add it via pip:

pip install pandas

This library provides the DataFrame structure, which represents data in a tabular format similar to spreadsheets but optimized for programmatic access. It includes built-in methods for reading CSV files, merging datasets, and filtering data based on conditions.

Step-by-Step Implementation

The most reliable way to compare two CSV files for duplicates is to perform an outer merge. An outer merge combines all records from both DataFrames, adding a suffix to column names to distinguish their origin. Rows that appear in both files will have values for both source and reference columns, while rows unique to one file will have nulls in the other's columns.

  1. Load the CSV Files: Use pandas.read_csv() to load both files into memory. Ensure that the column names match exactly between the two files for accurate comparison.
  2. Perform Outer Merge: Use pd.merge() with how='outer'. Specify on=list_of_columns to define which columns constitute a "duplicate." For example, if a row is considered a duplicate only if both the 'ID' and 'Name' match, specify those columns.
  3. Identify Unique Rows: After merging, check which columns have null values. Rows where the reference columns are null exist only in the source file. Conversely, rows where source columns are null exist only in the reference file.
  4. Filter and Save: Create new DataFrames containing only the desired unique rows and save them to new CSV files using .to_csv().

Code Example

Here is a concrete example of how to implement this logic. Assume we want to find rows in source.csv that are not present in reference.csv.

import pandas as pd

# Load the datasets
source_df = pd.read_csv('source.csv')
reference_df = pd.read_csv('reference.csv')

# Define columns to compare
compare_cols = ['id', 'email']

# Perform outer merge
merged_df = pd.merge(
    source_df, 
    reference_df, 
    on=compare_cols, 
    how='outer', 
    indicator=True
)

# Filter for rows only in source
unique_to_source = merged_df[merged_df['_merge'] == 'left_only']

# Drop the helper column and save
unique_to_source.drop(columns=['_merge']).to_csv('unique_source.csv', index=False)

In this code, the indicator=True parameter adds a special column named _merge that tells us the origin of each row. The value 'left_only' indicates the row was found only in the first DataFrame (the source). This method is efficient because it leverages vectorized operations within pandas rather than slow iterative loops.

Handling Edge Cases

Real-world data often contains inconsistencies that can break simple comparisons. Whitespace differences, case sensitivity, and missing values can lead to false negatives where identical data is treated as unique. To mitigate this, clean your data before merging. Convert string columns to lowercase and strip whitespace using .str.strip().str.lower().

Additionally, consider the performance implications. If your CSV files are extremely large (e.g., over 1GB), loading them entirely into memory might cause crashes. In such cases, consider processing the files in chunks using the chunksize parameter in read_csv, or use more specialized tools like polars which offer out-of-core processing capabilities.

For more insights on handling CSV issues in Python, you might find Python Script Keeps Closing and Does Not Make a New CSV File helpful, as it addresses common runtime errors during file operations.

Alternative Approaches

If you prefer not to use Python, command-line tools like awk or sort combined with uniq can also perform deduplication. However, these tools require careful handling of headers and delimiters, making them less user-friendly for complex multi-column comparisons. Another alternative is using database imports, where you can load both CSVs into SQLite or PostgreSQL and run SQL queries to find differences using EXCEPT or NOT EXISTS clauses.

Frequently Asked Questions

What if my CSV files have different column orders?

Pandas aligns columns by name, not position, so different orders do not matter as long as the header names are identical. If headers differ slightly, rename them using df.rename(columns={'old': 'new'}) before merging.

How do I handle case sensitivity in text fields?

To ensure "John" and "john" are treated as duplicates, convert relevant string columns to lowercase before merging. Use df[col] = df[col].str.lower() for each text column involved in the comparison.

Can I compare more than two CSV files at once?

Yes, you can chain multiple merges or concatenate all files into a single DataFrame and then use drop_duplicates() with subset parameters. However, pairwise comparison remains clearer for identifying specific origins of duplicates.

What if I get a MemoryError?

This occurs when files exceed available RAM. Consider using dask.dataframe which provides a pandas-like interface for larger-than-memory datasets, or process files in smaller chunks.

Does this method preserve the original order of rows?

Merging may reorder rows based on hash algorithms used internally. If preserving order is critical, reset the index after filtering: df.reset_index(drop=True).

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More