34
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Pandas で Multi-Index の特定のレベルの値を取得する

Last updated at Posted at 2018-09-03

いつも忘れてしまうのでメモ。

やりたいこと

例えば以下のような Multi-Index な Pandas DataFrame があったとする。

import pandas as pd
from itertools import product

keys = ['key1', 'key2']
df = pd.DataFrame(list(product(list('ABC'), list('DEF'))), columns=keys).set_index(keys)
df['val'] = None

ここで「key1A の行だけフィルタリングしたい」という場合、どうすればいいか。

解決策

pandas.MultiIndex.get_level_values というメソッドを使うと、Multi-Index の値にアクセスできる。

df.index.get_level_values('key1')  #=> Index(['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'], dtype='object', name='key1')

フィルタリングする場合はこう。

df[df.index.get_level_values('key1') == 'A']

[追記] 補足

フィルタリングするだけなら .loc にタプル渡すだけでもできた。

df.loc[('A',)]

参考

34
18
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
34
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?