The Wayback Machine - https://web.archive.org/web/20240918164320/https://www.geeksforgeeks.org/python-pandas-dataframe-drop_duplicates/
Open In App

Python | Pandas dataframe.drop_duplicates()

Last Updated : 10 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Pandas drop_duplicates() method helps in removing duplicates from the Pandas Dataframe In Python.

dataframe.drop_duplicates() Syntax in Python

Syntax: DataFrame.drop_duplicates(subset=None, keep=’first’, inplace=False)

Parameters:

  • subset: Subset takes a column or list of column label. It’s default value is none. After passing columns, it will consider them only for duplicates. 
  • keep: keep is to control how to consider duplicate value. It has only three distinct value and default is ‘first’. 
    • If ‘first‘, it considers first value as unique and rest of the same values as duplicate.
    • If ‘last‘, it considers last value as unique and rest of the same values as duplicate.
    • If False, it consider all of the same values as duplicates
  • inplace: Boolean values, removes rows with duplicates if True.

Return type: DataFrame with removed duplicate rows depending on Arguments passed. 

Python dataframe.drop_duplicates() Example

Below, we are discussing example of dataframe.drop_duplicates() method as its also use for Removing duplicates with Pandas in Python, example are :

Pandas DataFrame Drop Duplicates

As we can see one of the TeamA and team has been dropped due to duplicate value.

Python3

import pandas as pd

data = {
    "A": ["TeamA", "TeamB", "TeamB", "TeamC", "TeamA"],
    "B": [50, 40, 40, 30, 50],
    "C": [True, False, False, False, True]
}

df = pd.DataFrame(data)

display(df.drop_duplicates())

Output: 

    A        B    C
0 TeamA 50 True
1 TeamB 40 False
3 TeamC 30 False

Managing Duplicate Data Using dataframe.drop_duplicates()

In this example , we manages student data, showcasing techniques to removing duplicates with Pandas in Python, removing all duplicates, and deleting duplicates based on specific columns then the last part demonstrates making names case-insensitive while preserving the first occurrence.

Python3

import pandas as pd

# Sample data for student names and ages
students_data = {
    'Name': ["Alice", "Bob", "Charlie", "David", "Alice", "Eva", "Bob"],
    'Age': [20, 22, 21, 23, 20, 19, 22],
    'Grade': [85, 90, 78, 92, 85, 88, 90],
    'Attendance': [95, 92, 88, 93, 95, 96, 92]
}

# Create a DataFrame
students_df = pd.DataFrame(students_data)
print(students_df)

# Remove all duplicate rows
students_df_no_duplicates = students_df.drop_duplicates(keep=False)
print(students_df_no_duplicates)

# Delete duplicate rows based on specific columns (Name and Age)
students_df_specific_columns = students_df.drop_duplicates(subset=["Name", "Age"], keep=False)
print(students_df_specific_columns)

# Using DataFrame.apply() and lambda function to make names case-insensitive and keep the first occurrence
students_df_case_insensitive = students_df.apply(lambda x: x.astype(str).str.lower()).drop_duplicates(subset=['Name', 'Age'], keep='first')
print(students_df_case_insensitive)

Output:

     Name  Age  Grade  Attendance
0 Alice 20 85 95
1 Bob 22 90 92
2 Charlie 21 78 88
3 David 23 92 93
4 Alice 20 85 95
5 Eva 19 88 96
6 Bob 22 90 92

Name Age Grade Attendance
2 Charlie 21 78 88
3 David 23 92 93
5 Eva 19 88 96

Name Age Grade Attendance
5 Eva 19 88 96

Name Age Grade Attendance
5 Eva 19 88 96

To download the CSV file used, Click Here. 

Removing Rows with the Same First Name 

In the following example, rows having the same First Name are removed and a new data frame is returned.

Python3

# importing pandas package
import pandas as pd

# making data frame from csv file
data = pd.read_csv("employees.csv")

# sorting by first name
data.sort_values("First Name", inplace=True)

# dropping ALL duplicate values
data.drop_duplicates(subset="First Name",
                     keep=False, inplace=True)

# displaying data
data

Output: 

As shown in the image, the rows with the same names were removed from a data frame. 
 


Removing Rows with all Duplicate Values

In this example, rows having all values will be removed. Since the CSV file isn’t having such a row, a random row is duplicated and inserted into the data frame first.

Python3

# length before adding row
length1 = len(data)

# manually inserting duplicate of a row of row 440
data.loc[1001] = [data["First Name"][440],
                  data["Gender"][440],
                  data["Start Date"][440],
                  data["Last Login Time"][440],
                  data["Salary"][440],
                  data["Bonus %"][440],
                  data["Senior Management"][440],
                  data["Team"][440]]

# length after adding row
length2 = len(data)

# sorting by first name
data.sort_values("First Name", inplace=True)

# dropping duplicate values
data.drop_duplicates(keep=False, inplace=True)

# length after removing duplicates
length3 = len(data)

# printing all data frame lengths
print(length1, length2, length3)

Output: 

As shown in the output image, the length after removing duplicates is 999. Since the keep parameter was set to False, all of the duplicate rows were removed.
 

Python | Pandas dataframe.drop_duplicates() – FAQs

What does drop_duplicates do in Python?

The drop_duplicates() method in pandas is used to remove duplicate rows from a DataFrame. By default, this method considers all columns to identify duplicates, but you can specify particular columns to look for duplicates. When duplicates are found, only the first occurrence is kept, and the rest are dropped unless specified otherwise.

Example:

import pandas as pd

df = pd.DataFrame({
'A': [1, 2, 2, 3, 3, 3],
'B': ['a', 'b', 'b', 'c', 'c', 'c']
})

# Remove duplicate rows
clean_df = df.drop_duplicates()
print(clean_df)

How to Remove Duplicates in a DataFrame in Python?

To remove duplicates from a DataFrame, you can use the drop_duplicates() method. This method allows you to specify whether to drop duplicates across all columns or just a subset.

Example:

# Remove duplicates considering only column 'A'
clean_df = df.drop_duplicates(subset=['A'])
print(clean_df)

What is the Fastest Way to Remove Duplicates in Python?

The fastest way to remove duplicates for large datasets typically involves using pandas’ drop_duplicates() due to its efficient implementation. For smaller datasets or lists, converting a list to a set is a quick way to remove duplicates, but this only works if the order of the elements is not important, and all elements are hashable.

Example using set:

my_list = [1, 2, 2, 3, 4, 4]
unique_items = list(set(my_list))
print(unique_items)

How Do I Merge Two DataFrames and Delete Duplicates?

To merge two DataFrames and remove duplicates, you can use merge() followed by drop_duplicates(). This ensures that the merged DataFrame does not contain duplicate rows.

Example:

df1 = pd.DataFrame({
'A': [1, 2, 3],
'B': ['a', 'b', 'c']
})

df2 = pd.DataFrame({
'A': [4, 2, 3],
'B': ['d', 'b', 'c']
})

# Merge DataFrames and remove duplicates
merged_df = pd.merge(df1, df2, how='outer').drop_duplicates()
print(merged_df)

What is the Difference Between duplicated and drop_duplicates in pandas?

Example:

print(df.duplicated())
  • duplicated(): This method returns a boolean Series indicating whether each row is a duplicate (True) or not (False). This is useful when you need to identify duplicates without actually removing them from the DataFrame.
  • drop_duplicates(): This method removes the duplicate rows from the DataFrame and returns a new DataFrame with only unique rows or modifies the original DataFrame in place if inplace=True is specified.

Example:

df.drop_duplicates(inplace=True)

Both methods can operate on the entire DataFrame or on specific columns specified by the subset parameter and can be controlled further by parameters like keep, which can specify whether to keep the first occurrence, the last, or none of the duplicates.



Previous Article
Next Article

Similar Reads

What is the Equivalent of DataFrame.drop_duplicates() from Pandas in Polars?
In data analysis, data manipulation is a critical task and sometimes involves removing duplicates from the data. Removing duplicate elements is crucial as it can affect the program, making it look perfect even though in reality it is flawed. Pandas, a popular data manipulation library in Python, has the drop_duplicates function which can remove dup
4 min read
Python | Pandas Index.drop_duplicates()
Pandas Index.drop_duplicates() function return Index with duplicate values removed in Python. Syntax of Pandas Index.drop_duplicates() Syntax: Index.drop_duplicates(labels, errors='raise') Parameters : keep : {‘first’, ‘last’, False} ‘first’ : Drop duplicates except for the first occurrence.(default)‘last’ : Drop duplicates except for the last occu
2 min read
Python | Pandas TimedeltaIndex.drop_duplicates
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas TimedeltaIndex.drop_duplicates() function return Index with duplicate values removed. The function provides the flexibility to ch
2 min read
Python | Pandas Series.drop_duplicates()
Pandas Series.drop_duplicates() function returns a series object with duplicate values removed from the given series object. Syntax: Series.drop_duplicates(keep='first', inplace=False) Parameter : keep : {‘first’, ‘last’, False}, default ‘first’ inplace : If True, performs operation inplace and returns None. Returns : deduplicated : Series Example
2 min read
Python | Pandas DataFrame.fillna() to replace Null values in dataframe
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Sometimes csv file has null values, which are later displayed as NaN in Data Frame. Just like the pandas dropna() method manages and rem
5 min read
Difference Between Spark DataFrame and Pandas DataFrame
Dataframe represents a table of data with rows and columns, Dataframe concepts never change in any Programming language, however, Spark Dataframe and Pandas Dataframe are quite different. In this article, we are going to see the difference between Spark dataframe and Pandas Dataframe. Pandas DataFrame Pandas is an open-source Python library based o
3 min read
Pandas Dataframe.to_numpy() - Convert dataframe to Numpy array
Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). This data structure can be converted to NumPy ndarray with the help of the DataFrame.to_numpy() method. In this article we will see how to convert dataframe to numpy array. Syntax of Pandas DataFrame.to_numpy()
3 min read
Convert given Pandas series into a dataframe with its index as another column on the dataframe
First of all, let we understand that what are pandas series. Pandas Series are the type of array data structure. It is one dimensional data structure. It is capable of holding data of any type such as string, integer, float etc. A Series can be created using Series constructor. Syntax: pandas.Series(data, index, dtype, copy) Return: Series object.
1 min read
How to Convert Wide Dataframe to Tidy Dataframe with Pandas stack()?
We might sometimes need a tidy/long-form of data for data analysis. So, in python's library Pandas there are a few ways to reshape a dataframe which is in wide form into a dataframe in long/tidy form. Here, we will discuss converting data from a wide form into a long-form using the pandas function stack(). stack() mainly stacks the specified index
4 min read
Replace values of a DataFrame with the value of another DataFrame in Pandas
In this article, we will learn how we can replace values of a DataFrame with the value of another DataFrame using pandas. It can be done using the DataFrame.replace() method. It is used to replace a regex, string, list, series, number, dictionary, etc. from a DataFrame, Values of the DataFrame method are get replaced with another value dynamically.
4 min read
Converting Pandas Dataframe To Dask Dataframe
In this article, we will delve into the process of converting a Pandas DataFrame to a Dask DataFrame in Python through several straightforward methods. This conversion is particularly crucial when dealing with large datasets, as Dask provides parallel and distributed computing capabilities, allowing for efficient handling of substantial data volume
3 min read
Pandas Dataframe rank() | Rank DataFrame Entries
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.  Pandas DataFrame rank() method returns a rank of every respective entry (1 through n) along an axis of the DataFrame passed. The rank is retu
3 min read
Pandas DataFrame to_dict() Method | Convert DataFrame to Dictionary
Python is a great language for doing data analysis because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.  Pandas .to_dict() method is used to convert a DataFrame into a dictionary of series or list-like data type depending on the orient parameter. Exam
3 min read
Pandas DataFrame assign() Method | Create new Columns in DataFrame
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages, making importing and analyzing data much easier. The Dataframe.assign() method assigns new columns to a DataFrame, returning a new object (a copy) with the new columns added to the original one
4 min read
Pandas DataFrame hist() Method | Create Histogram in Pandas
A histogram is a graphical representation of the numerical data. Sometimes you'll want to share data insights with someone, and using graphical representations has become the industry standard. Pandas.DataFrame.hist() function plots the histogram of a given Data frame. It is useful in understanding the distribution of numeric variables. This functi
4 min read
Pandas DataFrame iterrows() Method | Pandas Method
Pandas DataFrame iterrows() iterates over a Pandas DataFrame rows in the form of (index, series) pair. This function iterates over the data frame column, it will return a tuple with the column name and content in the form of a series. Example: Python Code import pandas as pd df = pd.DataFrame({ 'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 32, 3
2 min read
Pandas DataFrame interpolate() Method | Pandas Method
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.  Python Pandas interpolate() method is used to fill NaN values in the DataFrame or Series using various interpolation techniques to fill the m
3 min read
Pandas DataFrame duplicated() Method | Pandas Method
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas duplicated() method identifies duplicated rows in a DataFrame. It returns a boolean series which is True only for unique rows. Ex
3 min read
Filter Pandas dataframe in Python using 'in' and 'not in'
The in and not in operators can be used with Pandas DataFrames to check if a given value or set of values is present in the DataFrame or not using Python. The in-operator returns a boolean value indicating whether the specified value is present in the DataFrame, while the not-in-operator returns a boolean value indicating whether the specified valu
3 min read
Python | Pandas DataFrame.reset_index()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas reset_index() is a method to reset index of a Data Frame. reset_index() method sets a list of integer ranging from 0 to length of
2 min read
Python | Pandas dataframe.notna()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.Pandas dataframe.notna() function detects existing/ non-missing values in the dataframe. The function returns a boolean object having the
2 min read
Python | Pandas dataframe.notnull()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.Pandas dataframe.notnull() function detects existing/ non-missing values in the dataframe. The function returns a boolean object having t
2 min read
Python | Pandas dataframe.reindex_like()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas dataframe.reindex_like() function return an object with matching indices to myself. Any non-matching indexes are filled with NaN
3 min read
Python | Pandas Dataframe.sort_values() | Set-2
Prerequisite: Pandas DataFrame.sort_values() | Set-1 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages, and makes importing and analyzing data much easier. Pandas sort_values() function sorts a data frame in Ascending or Descending order
3 min read
Python | Pandas Dataframe.sample()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas sample() is used to generate a sample random row or column from the function caller data frame. Syntax: DataFrame.sample(n=None,
2 min read
Python | Pandas DataFrame.nlargest()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas nlargest() method is used to get n largest values from a data frame or a series. Syntax: DataFrame.nlargest(n, columns, keep='fir
2 min read
Python | Pandas DataFrame.nsmallest()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.Pandas nsmallest() method is used to get n least values from a data frame or a series. Syntax: DataFrame.nsmallest(n, columns, keep='firs
2 min read
Python | Pandas Dataframe.pop()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.Pandas Pop() method is common in most of the data structures but pop() method is a little bit different from the rest. In a stack, pop do
2 min read
Python | Pandas Dataframe.rename()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas rename() method is used to rename any index, column or row. Renaming of column can also be done by dataframe.columns = [#list]. B
3 min read
Python | Pandas dataframe.skew()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas dataframe.skew() function return unbiased skew over requested axis Normalized by N-1. Skewness is a measure of the asymmetry of t
2 min read