Andy Hayden 的回答 (index.levels[blah]) 在某些情况下非常有用,但在其他情况下可能会导致奇怪的行为。我的理解是,Pandas 会尽可能地“重用”索引,以避免大量索引相似的 DataFrame 的索引占用内存空间。结果,I've found the following annoying behavior:
import pandas as pd
import numpy as np
np.random.seed(0)
idx = pd.MultiIndex.from_product([['John', 'Josh', 'Alex'], list('abcde')],
names=['Person', 'Letter'])
large = pd.DataFrame(data=np.random.randn(15, 2),
index=idx,
columns=['one', 'two'])
small = large.loc[['Jo'==d[0:2] for d in large.index.get_level_values('Person')]]
print small.index.levels[0]
print large.index.levels[0]
哪些输出
Index([u'Alex', u'John', u'Josh'], dtype='object')
Index([u'Alex', u'John', u'Josh'], dtype='object')
而不是预期
Index([u'John', u'Josh'], dtype='object')
Index([u'Alex', u'John', u'Josh'], dtype='object')
正如一个人在另一个帖子中指出的那样,一个看起来非常自然且工作正常的习语是:
small.index.get_level_values('Person').unique()
large.index.get_level_values('Person').unique()
我希望这可以帮助其他人避开我遇到的超级意外行为。