はじめに
PandasのDataFrameからIndexが重複している行を削除する方法を紹介します。
Indexが重複している行を削除
pandas.Index.duplicated
を使ってIndexが重複した行を削除します。
やり方は下記の通りです。
# 重複した最初の行を残す場合(デフォルト)
df = df[~df.index.duplicated(keep='first')]
# 重複した最後の行を残す場合
df = df[~df.index.duplicated(keep='last')]
pandas.Index.duplicated — pandas 1.5.0 documentation
試してみる
実際にどのようになるか試してみます。
まずはDataFrameを用意します。
import pandas as pd
idx = pd.Index(['lama', 'cow', 'lama', 'beetle', 'cow'])
data = {'A' : range(5), 'B' : range(5)}
df = pd.DataFrame(data=data, index=idx)
A | B | |
---|---|---|
lama | 0 | 0 |
cow | 1 | 1 |
lama | 2 | 2 |
beetle | 3 | 3 |
cow | 4 | 4 |
Indexが重複した中から最初の行を残すと下記のようになります。
df = df[~df.index.duplicated(keep='first')]
A | B | |
---|---|---|
lama | 0 | 0 |
cow | 1 | 1 |
beetle | 3 | 3 |
一方で、Indexが重複した中から最後の行を残すと下記のようになります。
df = df[~df.index.duplicated(keep='last')]
A | B | |
---|---|---|
lama | 2 | 2 |
beetle | 3 | 3 |
cow | 4 | 4 |