【发布时间】:2014-08-17 13:18:20
【问题描述】:
假设我有一个大型数据框large,它的行上有一个 MultiIndex。我通过只选择一些行来减少这个数据框并将结果分配给small。特别是,small 在其 MultiIndex 的第 0 级中的行上的不同值比 large 少。
然后,我想要在 small 的行上的 MultiIndex 的第 0 级中的不同值的列表,所以我调用 small.index.levels[0]。结果很奇怪:它返回与large.index.levels[0] 相同的内容,尽管值应该更少。
发生了什么事?
MWE:
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')
【问题讨论】:
标签: python pandas multi-index