Detect and save duplicated rows in pandas dataframe

Viewed 76

I have a pandas dataframe with multiple columns in the below format:

Id    Year    Month   
123   2021    02
123   2021    02
345   2021    03
345   2021    03
567   2021    04

I am trying to detect duplicate rows based on "Id" column and keep both the rows. Hence, in the result it has to be

Id    Year    Month   
123   2021    02
123   2021    02
345   2021    03
345   2021    03

I am trying this code:

df_duplicates = df[df.duplicated('Id')]

But it does not yield the expected results. Any suggestions would be appreciated.

1 Answers

Use keep=False:

df[df.duplicated('Id', keep=False)]
Related