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 dublicates in pandas but keep duplicates between years

I have a dataset like this

ID     Year    Day
 1     2001    150
 2     2001    140
 3     2001    120
 3     2002    160
 3     2002    160
 3     2017     75
 3     2017     75
 4     2017     80

I would like to drop the duplicates within each year, but keep those were the year differs. End result would be this:

 1     2001    150
 2     2001    140
 3     2001    120
 3     2002    160
 3     2017     75
 4     2017     80

I tried to do something like this in python with my pandas dataframe:

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

data = read_csv('data.csv')
data = data.drop_duplicates(subset = ['ID'], keep = first)

But this will delete duplicates between years, while I would like to keep this.

How do I keep the duplicates between years?

>Solution :

add ‘year’ in your subset.

data.drop_duplicates(subset = ['ID','Year'], keep = 'first')
    ID  Year    Day
0   1   2001    150
1   2   2001    140
2   3   2001    120
3   3   2002    160
5   3   2017    75
7   4   2017    80
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