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

Identify duplicates and assign similar index in Pandas DataFrame

Suppose that I have a sample data set that can be generated using code below

# Sample DataFrame with duplicate rows
data = {'A': [1, 2, 1, 3, 1, 2, 3, 2],
        'B': [4, 5, 4, 6, 4, 5, 6, 5],
        'C': [1, 2, 3, 4, 5, 6, 7, 8]}
df = pd.DataFrame(data)

In above dataframe I want to assign duplicate rows similar index. For index 0 would be assigned to rows 0, 1 and 4. Similarly index 1 would be assigned to rows 1, 5 and 7. Duplicates should be identified using only column A and B

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 :

Use groupby().ngroup:

df.index = df.groupby(['A','B']).ngroup()

Output:

   A  B  C
0  1  4  1
1  2  5  2
0  1  4  3
2  3  6  4
0  1  4  5
1  2  5  6
2  3  6  7
1  2  5  8
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