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

2022.09.23
2024.03.24
プログラミング
pandasPython

はじめに

PandasのDataFrameからIndexが重複している行を削除する方法を紹介します。

Indexが重複している行を削除

pandas.Index.duplicatedを使ってIndexが重複した行を削除します。

やり方は下記の通りです。

1# 重複した最初の行を残す場合(デフォルト)
2df = df[~df.index.duplicated(keep='first')]
3
4# 重複した最後の行を残す場合
5df = df[~df.index.duplicated(keep='last')]

pandas.Index.duplicated — pandas 2.2.2 documentation

試してみる

実際にどのようになるか試してみます。

まずはDataFrameを用意します。

1import pandas as pd
2
3idx = pd.Index(['lama', 'cow', 'lama', 'beetle', 'cow'])
4data = {'A' : range(5), 'B' : range(5)}
5df = pd.DataFrame(data=data, index=idx)
AB
lama00
cow11
lama22
beetle33
cow44

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

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

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

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

参考

Support

\ この記事が役に立ったと思ったら、サポートお願いします! /

buy me a coffee
Share

Profile

author

Masa

都内のIT企業で働くエンジニア
自分が学んだことをブログでわかりやすく発信していきながらスキルアップを目指していきます!

buy me a coffee