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.
An important part of Data analysis is analyzing Duplicate Values and removing them. Pandas duplicated() method helps in analyzing duplicate values only. It returns a boolean series which is True only for Unique elements.
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 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.Â
Â
To download the CSV file used, Click Here.
Example #1: Returning a boolean series
In the following example, a boolean series is returned on the basis of duplicate values in the First Name column.
Â
Python
# importing pandas packageimport pandas as pdÂ
# making data frame from csv filedata = pd.read_csv("employees.csv")Â
# sorting by first namedata.sort_values("First Name", inplace = True)Â
# making a bool seriesbool_series = data["First Name"].duplicated()Â
# displaying datadata.head()Â
# display datadata[bool_series] |
Output:Â
As shown in the output image, since the keep parameter was default that is ‘first’, hence whenever the name is occurred, the first one is considered Unique and res Duplicate.
Â
Â
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 data.
Â
Python
# importing pandas packageimport pandas as pdÂ
# making data frame from csv filedata = pd.read_csv("employees.csv")Â
# sorting by first namedata.sort_values("First Name", inplace = True)Â
# making a bool seriesbool_series = data["First Name"].duplicated(keep = False)Â
# bool seriesbool_seriesÂ
# passing NOT of bool series to see unique values onlydata = data[~bool_series]Â
# displaying datadata.info()data |
Output:Â
Since the duplicated() method returns False for Duplicates, the NOT of the series is taken to see unique value in Data Frame.Â
Â
Â

