The Wayback Machine - https://web.archive.org/web/20240915123520/https://www.geeksforgeeks.org/pandas-dataframe-duplicated/
Open In App

Pandas DataFrame duplicated() Method | Pandas Method

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

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.

Example:

Python3




import pandas as pd
df = pd.DataFrame({
    'Name': ['Alice', 'Bob', 'Alice', 'Charlie'],
    'Age': [25, 32, 25, 37]
})
duplicates = df[df.duplicated()]
print(duplicates)


Output:

Name  Age
2  Alice   25

Syntax 

Syntax: DataFrame.duplicated(subset=None, keep=’first’)

Parameters:  

  • 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: Controls how to consider duplicate value. It has only three distinct values and the default is ‘first’. 
    –> If ‘first‘, it considers the first value as unique and the rest of the same values as duplicate. 
    –> If ‘last‘, it considers the last value as unique and the rest of the same values as duplicate. 
    –> If False, it considers all of the same values as duplicates. 

Returns: A series with boolean values for each row in the DataFrame 

To download the CSV file used, Click Here.

Examples

Let’s look at some examples of the duplicated method in Pandas library used to identify duplicated rows in a DataFrame.

Example 1: Returning a boolean series

In the following example, a boolean series is returned based on duplicate values in the First Name column. 

Python




# 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)
  
# making a bool series
bool_series = data["First Name"].duplicated()
  
# displaying data
data.head()
  
# display data
data[bool_series]


Output: 
As shown in the output image, since the keep parameter was a default that is ‘first‘, hence whenever the name occurs, the first one is considered Unique, and the rest Duplicate. 

 duplicated method example output
 
Example 2: Removing duplicates 

In this example, the keep parameter is set to False, so that only Unique values are taken and the duplicate values are removed from DataFrame. 

Python




# 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)
  
# making a bool series
bool_series = data["First Name"].duplicated(keep = False)
  
# bool series
bool_series
  
# passing NOT of bool series to see unique values only
data = data[~bool_series]
  
# displaying data
data.info()
data


Output: 
Since the duplicated() method returns False for duplicates, the NOT of the series is taken to see the unique values in the DataFrame. 
 

removing duplicate value with duplicated output



Previous Article
Next Article

Similar Reads

Rename Duplicated Columns after Join in Pyspark dataframe
In this article, we are going to learn how to rename duplicate columns after join in Pyspark data frame in Python. A distributed collection of data grouped into named columns is known as a Pyspark data frame. While handling a lot of data, we observe that not all data is coming from one data frame, thus there is a need to merge two or more data fram
4 min read
PySpark Dataframe distinguish columns with duplicated name
In this article, we are going to learn how to distinguish columns with duplicated names in the Pyspark data frame in Python. A dispersed collection of data grouped into named columns is known as the Pyspark data frame. While working in Pyspark, there occurs various situations in which we get the data frame that has various columns with duplicate na
5 min read
Python | Pandas TimedeltaIndex.duplicated
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.duplicated() function detects duplicate values in the given TimedeltaIndex object. It return a boolean np.ndarray
2 min read
Python | Pandas Series.duplicated()
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer and label-based indexing and provides a host of methods for performing operations involving the index. Pandas Series.duplicated() function indicate duplicate Series values. The duplicated values ar
2 min read
Prevent duplicated columns when joining two Pandas DataFrames
Column duplication usually occurs when the two data frames have columns with the same name and when the columns are not used in the JOIN statement. In this article, let us discuss the three different methods in which we can prevent duplication of columns when joining two data frames. Syntax: pandas.merge(left, right, how='inner', on=None, left_on=N
5 min read
Python | Pandas Index.duplicated()
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 Index.duplicated() function returns Index object with the duplicate values remove. Duplicated values are indicated as True values
2 min read
Python Set difference to find lost element from a duplicated array
Given two arrays which are duplicates of each other except one element, that is one element from one of the array is missing, we need to find that missing element. Examples: Input: A = [1, 4, 5, 7, 9] B = [4, 5, 7, 9] Output: [1] 1 is missing from second array. Input: A = [2, 3, 4, 5 B = 2, 3, 4, 5, 6] Output: [6] 6 is missing from first array. We
1 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
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
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
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 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
How to select the rows of a dataframe using the indices of another dataframe?
Prerequisites: PandasRandom Using Pandas module it is possible to select rows from a data frame using indices from another data frame. This article discusses that in detail. It is advised to implement all the codes in jupyter notebook for easy implementation. Approach:Import moduleCreate first data frame. In the example given below choice(), randin
2 min read
How to slice a PySpark dataframe in two row-wise dataframe?
In this article, we are going to learn how to slice a PySpark DataFrame into two row-wise. Slicing a DataFrame is getting a subset containing all rows from one index to another. Method 1: Using limit() and subtract() functions In this method, we first make a PySpark DataFrame with precoded data using createDataFrame(). We then use limit() function
4 min read
How to Transform Spark DataFrame to Polars DataFrame?
Apache Spark and Polars are powerful data processing libraries that cater to different needs. Spark excels in distributed computing and is widely used for big data processing, while Polars, a newer library, is designed for fast, single-machine data processing, leveraging Rust for performance. Sometimes, you might want to transform a Spark DataFrame
3 min read
Pandas DataFrame.dropna() Method
Pandas is one of the packages that makes importing and analyzing data much easier. Sometimes CSV file has null values, which are later displayed as NaN in Pandas DataFrame. Pandas dropna() method allows the user to analyze and drop Rows/Columns with Null values in different ways. Pandas DataFrame.dropna() Syntax Syntax: DataFrameName.dropna(axis=0,
3 min read
Python | Pandas Dataframe/Series.head() 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 head() method is used to return top n (5 by default) rows of a data frame or series. Syntax: Dataframe.head(n=5) Parameters: n: i
2 min read
Python | Pandas Dataframe/Series.tail() 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 tail() method is used to return bottom n (5 by default) rows of a data frame or series. Syntax: Dataframe.tail(n=5) Parameters: n
2 min read
Pandas dataframe.nunique() 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 DataFrame.nunique Syntax Pandas dataframe.nunique() function returns a Series with a number of distinct observations over the req
2 min read
Pandas DataFrame.to_sparse() Method
Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Arithmetic operations align on both row and column labels. It can be thought of as a dict-like container for Series objects. This is the primary data structure of the Pandas. Pandas DataFrame.to_sparse Pandas Da
2 min read
Python | Pandas DataFrame.to_html() method
With help of DataFrame.to_html() method, we can get the html format of a dataframe by using DataFrame.to_html() method. Syntax : DataFrame.to_html() Return : Return the html format of a dataframe. Example #1 : In this example we can say that by using DataFrame.to_html() method, we are able to get the html format of a dataframe. # import DataFrame i
1 min read
Python | Pandas DataFrame.to_latex() method
With the help of DataFrame.to_latex() method, We can get the dataframe in the form of latex document which we can open as a separate file by using DataFrame.to_latex() method. Syntax : DataFrame.to_latex() Return : Return the dataframe as a latex document. Example #1 : In this example we can say that by using DataFrame.to_latex() method, we are abl
1 min read