Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

drop duplicated rows and add a count for the repeat count

I would like to add a repeat count for the duplicate rows. current example only drop duplicate rows.

import re
import pandas as pd

data = [
    ['A','B','C'],
    ['A','B','C'],
    ['A','D','C'],
    ['A','D','C']
]

df = pd.DataFrame(data,columns=['x1','x2','x3'])
print(df)

df1 = df.drop_duplicates(keep='first')
print(df1)

expected output:

:   x1 x2 x3
: 0  A  B  C
: 1  A  B  C
: 2  A  D  C
: 3  A  D  C
:   x1 x2 x3 count
: 0  A  B  C 2
: 2  A  D  C 2

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try this line:

df1 = df.groupby(['x1', 'x2', 'x3']).size().reset_index(name='count')

Here, we first group_by x1, x2, and x3, so there will be no duplicates and then count how many duplicates are grouped.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading