hakuna_code
hakuna_code

Reputation: 793

How to keep the first occurence of a value which is repeated in a dataframe in python?

The df looks like below:

A   B   C
1   8   23
2   8   22
3   8   45
4   9   45
5   6   12
6   11  10
7   11  12

I want to drop the repeated occurence of '8'. I know there is a way for removing all the repeated occurence. But how to specify a certain value?

Expected output:

A   B   C
1   8   23
4   9   45
5   6   12
6   11  10
7   11  12

Upvotes: 1

Views: 48

Answers (1)

anky
anky

Reputation: 75080

Use .duplicated() to identify duplicates with an & condition with the desired value to be removed and use ~ to turn False values to True and vice versa:

df[~(df['B'].duplicated() & df['B'].eq(8))]

   A   B   C
0  1   8  23
3  4   9  45
4  5   6  12
5  6  11  10
6  7  11  12

Upvotes: 4

Related Questions