Home >Backend Development >Python Tutorial >How to Remove Consecutive Duplicates in a Pandas Series?

How to Remove Consecutive Duplicates in a Pandas Series?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-13 01:49:02409browse

How to Remove Consecutive Duplicates in a Pandas Series?

Dropping Consecutive Duplicates in Pandas

To remove consecutive duplicates from a pandas Series, several methods can be employed.

Method 1: Using Shift

The most efficient approach is to leverage the shift() function:

a.loc[a.shift() != a]

This method compares the Series against its own shifted version, creating a boolean mask where consecutive duplicates are identified.

Method 2: Using Diff

An alternative method is to use the diff() function:

a.loc[a.diff() != 0]

However, this approach is slightly slower for large data sets.

Update:

It's important to note that using shift() with a default period of 1 is equivalent to shift(1). Therefore, the following code also produces the desired output:

a.loc[a.shift(1) != a]

By utilizing these methods, you can effectively remove consecutive duplicates from pandas Series, ensuring that only distinct values are retained.

The above is the detailed content of How to Remove Consecutive Duplicates in a Pandas Series?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn