【Pandas】DataFrameでIndexが重複している行を削除する

スポンサーリンク

はじめに

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)
AB
lama00
cow11
lama22
beetle33
cow44

Indexが重複した中から最初の行を残すと下記のようになります。

df = df[~df.index.duplicated(keep='first')]
AB
lama00
cow11
beetle33

一方で、Indexが重複した中から最後の行を残すと下記のようになります。

df = df[~df.index.duplicated(keep='last')]
AB
lama22
beetle33
cow44

参考

タイトルとURLをコピーしました