Concatenate Pandas DataFrames Without Duplicates
Last Updated :
15 Nov, 2024
Concatenating Pandas DataFrames refers to combining multiple DataFrames into one, either by stacking them vertically (rows) or horizontally (columns). However, when the DataFrames being combined have overlapping rows or columns, duplicates can occur. The core idea is simple: use the pd.concat method to concatenate the DataFrames and then apply the drop_duplicates method to remove any duplicate rows.
Removing Duplicate Rows Using drop_duplicates()
drop_duplicates() method checks for duplicate rows and removes them based on all columns by default. Let's understand with a quick example:
Python
import pandas as pd
df1 = pd.DataFrame({'ID': [1, 2], 'Name': ['Alice', 'Bob']})
df2 = pd.DataFrame({'ID': [2, 3], 'Name': ['Bob', 'Charlie']})
# Concatenate and remove duplicates
combined_df = pd.concat([df1, df2])
print(combined_df)
Output:

Concatenate Pandas DataFrames
After concatenating DataFrames let’s to remove duplicate rows that share similar content. The syntax is:
Python
combined_df= combined_df.drop_duplicates()
display(combined_df)
Output:

Concatenate Pandas DataFrames Without Duplicates
Using the concat() function followed by drop_duplicates() ensures that any duplicate rows are removed after combining the DataFrames. In this example, the row with ID=2 appears in both DataFrames, but after concatenation and removing duplicates, it only appears once in the final output.
Removing Duplicates Based on Specific Columns
If you only want to remove duplicates based on certain columns (and not the whole row), you can use the subset parameter. For instance, if you want to remove duplicates based only on the ID column while keeping other data intact, you can specify this using the subset parameter.
Python
# Remove duplicates based only on 'ID' column
combined_df = pd.concat([df1, df2]).drop_duplicates(subset='ID')
print(combined_df)
Output:
ID Name
0 1 Alice
1 2 Bob
1 3 Charlie
In this case, duplicates are removed based solely on the ID column. Notice that the the index is repeating which can issue while calling for the row.
Resetting Index After Concatenation
After concatenating and removing duplicates, it’s often useful to reset the index for better readability and further operations. This can be done using the reset_index() method with drop=True.
Python
# Reset index after removing duplicates
combined_df = combined_df.reset_index(drop=True)
print(combined_df)
Output:
ID Name
0 1 Alice
1 2 Bob
2 3 Charlie
Now, the index has been reset sequentially from zero.
Pandas Merge DataFrames Without Duplicates: Examples
Below are more examples which depict how to perform concatenation between two dataframes using pandas module without duplicates:
Example 1: In this example, two DataFrames with numeric data are concatenated, containing different sets of numbers, but one shared value exists in columnA. This would create duplicates if concatenated directly.
Python
# Importing pandas library
import pandas as pd
# loading dataframes
dataframe1 = pd.DataFrame({'columnA': [20, 30, 40],
'columnB': [200, 300, 400]})
dataframe2 = pd.DataFrame({'columnA': [50, 20, 60],
'columnB': [500, 200, 600]})
# Concatenating dataframes without duplicates
new_dataframe = pd.concat([dataframe1, dataframe2]).drop_duplicates()
# Display concatenated dataframe
new_dataframe
Output:

Example 2: The two dataframes represent individuals with names and ages. The row for “anjali, age 28” appears in both dataframes, which will lead to a duplicate.
Python
# Importing pandas library
import pandas as pd
# loading dataframes
dataframe1 = pd.DataFrame({'name': ['rahul', 'anjali', 'kajal'],
'age': [23, 28, 30]})
dataframe2 = pd.DataFrame({'name': ['devesh', 'rashi', 'anjali'],
'age': [20, 15, 28]})
# Concatenating two dataframes without duplicates
new_dataframe = pd.concat([dataframe1, dataframe2]).drop_duplicates()
# Resetting index
new_dataframe = new_dataframe.reset_index(drop=True)
# Display dataframe generated
new_dataframe
Output:

Overlapping name and age columns are merged, duplicates are removed, and the index is reset for a neater, continuous index sequence.
Example 3: Here is another example, which depicts how to concatenate two dataframes. Two dataframes list employees with their departments and designations, with one employee (“alisa”) in both dataframes. Concatenating would duplicate this entry.
Python
# Importing pandas library
import pandas as pd
# Loading dataframes
dataframe1 = pd.DataFrame({'empname': ['rohan', 'hina', 'alisa', ],
'department': ['IT', 'admin', 'finance', ],
'designation': ['Sr.developer', 'administrator', 'executive', ]})
dataframe2 = pd.DataFrame({'empname': ['rishi', 'huma', 'alisa', ],
'department': ['cyber security', 'HR', 'finance', ],
'designation': ['penetration tester', 'HR executive', 'executive', ]})
# Concatenating two dataframes without duplicates
new_dataframe = pd.concat([dataframe1, dataframe2]).drop_duplicates()
# Resetting index
new_dataframe = new_dataframe.reset_index(drop=True)
# Display dataframe generated
new_dataframe
Output:

Output dataset for the Example 3
After concatenation and removing duplicates, new_dataframe displays unique employee records. Resetting the index organizes rows cleanly, avoiding repeated entries.
Similar Reads
How to make div height expand with its content using CSS ?
When designing a webpage, ensuring that a div adjusts its height according to its content is important for creating a flexible and responsive layout. By using CSS, you can easily make a div adapt to varying content sizes, which is particularly useful when dealing with dynamic or unpredictable conten
3 min read
How to detect the change in DIV's dimension ?
The change in a div's dimension can be detected using 2 approaches: Method 1: Checking for changes using the ResizeObserver Interface The ResizeObserver Interface is used to report changes in dimensions of an element. The element to be tracked is first selected using jQuery. A ResizeObserver object
4 min read
How to Create a Half Page Background Image with CSS?
A half-page background image is an image that covers half of the viewport height. This can be useful for creating visually distinct sections on a webpage, especially for headers or introductory sections. These are the different approaches to creating a half-page background image using CSS: Table of
2 min read
How to Create a div that Contains Multiple Fixed-Size Images?
Creating a div that contains multiple fixed-size images involves defining a container (div) in HTML and applying CSS to set consistent dimensions for the images. This ensures that all images within the container maintain the same width and height, providing a uniform layout. ApproachHTML Structure:
2 min read
How to Create Equal Height Columns in CSS ?
Equal Height Columns in CSS refer to ensuring that multiple columns in a layout have the same height, regardless of the content inside each column. This can be achieved using modern CSS techniques like Flexbox, CSS Grid, or the Table display property. Table of Content Using FlexUsing GridUsing Table
3 min read
How to Specify Height to Fit-Content with Tailwind CSS ?
Specifying height to fit-content in Tailwind CSS means setting an element’s height to automatically adjust based on its content. Tailwind provides the h-fit utility class, which ensures the element's height dynamically adapts to its content's size. Adjusting Height with h-fit in Tailwind CSSThis app
2 min read
Resize an iframe based on the content
Resizing an iframe based on the content means automatically adjusting the iframe's height and/or width to fit the embedded content's dimensions. This prevents scrollbars and ensures the content is fully visible without manually setting fixed iframe sizes. Note: To open the source site to resize its
2 min read
How to Set Div Width to Fit Content using CSS?
To set the width of a div to fit its content using CSS, there are multiple approaches you can use. This is useful when you want the container to automatically adjust its size based on the content inside, rather than setting a fixed width. 1. Using Default CSS BehaviorBy default, a <div> in HTM
5 min read
How to Create Columns with the Same Height in Tailwind CSS ?
Creating columns of equal height is a common design requirement in web development. This need arises in scenarios like displaying a grid of cards or a list of items where each column should have the same height regardless of its content. Tailwind CSS, a utility-first CSS framework, provides several
2 min read
How to Create a 3-Column Layout Grid with CSS?
Grid in CSS is a powerful layout system that allows you to create complex, responsive designs with ease. By defining rows and columns, you can position elements precisely within a grid container. Using grid properties like grid-template-columns, you can create flexible and adaptive layouts, such as
3 min read
How to make div not larger than its contents using CSS?
There are three ways to achieve this problem: By default case Using inline-block property Using fit-content property in width and height Default Case: In HTML div is by default fit to content inside it. The example goes like this: Example 1: <!DOCTYPE html> <html lang = "en" dir =
3 min read
How to Create a 2-Column Layout Grid with CSS?
Creating a two-column layout is a common design pattern used in web development. This layout helps to organize content efficiently and is used across various types of websites. A 2-column layout divides the webpage into two sections, which can be useful for creating sidebars, main content areas, or
4 min read
How to create a Full-Page Background with CSS ?
To create a full-page background with CSS, set the body's height to `100vh` to cover the viewport, and add a background image using `background-image`. Ensure the image fills the entire viewport without distortion by setting 'background-size: cover'. Optionally, adjust 'background-position' and 'bac
2 min read
How to Create a Responsive CSS Grid Layout ?
Here are different ways to create a responsive grid layout with CSS. 1. Using auto-fill PropertyThis method can be used CSS Grid for a responsive layout. The grid-template-columns property adjusts columns based on space, keeping a minimum width of 200 pixels. Gaps between items are set with grid-gap
3 min read
How to Control the Size of an Image without Stretching in CSS ?
Controlling the size of an image while maintaining its aspect ratio is a common challenge in web design. Directly setting an image's width and height can lead to stretching or squashing, distorting the original aspect ratio. Fortunately, CSS offers several techniques to resize images without distort
2 min read
How to Increase Button Size in HTML Without CSS ?
To increase the button size in HTML without CSS, one can use JQuery and JavaScript language. In this article, we will explore both of these approaches with complete implementation in terms of examples and outputs. Table of Content Using jQueryUsing JavaScriptUsing jQueryIn this approach, we are usin
2 min read
How to Create Equal Width Table Cell Using CSS ?
Creating equal-width table cells using CSS refers to adjusting the table's layout so that all columns maintain the same width. This technique ensures a consistent and organized appearance, making the table content easier to read and visually balanced. Here we are following some common approaches: Ta
3 min read
How to Auto Adjust Table td Width from the Content in HTML?
HTML tables are needed to be displayed in responsiveness and adaptability across different screen sizes. Auto-adjusting table cell widths ensures that the table's layout adapts dynamically to the content, improving readability and usability. This can be done using different CSS properties like table
3 min read
Calculate the width of the text in JavaScript
Calculating the width of text in JavaScript refers to determining the pixel width that a specific string of text will occupy when rendered in a browser. This is commonly done using the Canvas API or by creating a hidden element with similar styling to measure the text. Here we have some common appro
3 min read