如何刪除 Pandas 中的連續重複項?

Barbara Streisand
發布: 2024-11-15 04:09:02
原創
115 人瀏覽過

How to Remove Consecutive Duplicates in Pandas?

Removing Consecutive Duplicates in Pandas

While Pandas' drop_duplicates() method is effective for eliminating all duplicate values, it does not discern consecutive occurrences. To address this limitation, there are efficient methods to selectively drop only consecutive duplicates.

One approach employs the shift function to compare the current value to the previous one:

a.loc[a.shift() != a]
登入後複製

This logic returns a mask where consecutive duplicates are characterized by False values. The loc method then selects only the rows with True values, effectively removing the consecutive duplicates.

Another method utilizes the diff function to detect changes:

a.loc[a.diff() != 0]
登入後複製

However, this approach is less efficient for large datasets due to the overhead associated with the differentiation calculation.

Update

It's worth noting that the default shift period is 1, so shift() and shift(1) produce equivalent results:

a.loc[a.shift(1) != a]
登入後複製

This ensures that the first consecutive value is correctly identified as a duplicate.

以上是如何刪除 Pandas 中的連續重複項?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板