假设我有一个大数据框large
行上有一个 MultiIndex。我通过仅选择某些行来缩减此数据框并将结果分配给small
。尤其,small
行上 MultiIndex 的第 0 级中的不同值少于large
.
然后我想要一个 MultiIndex 的第 0 级中的不同值的列表small
所以我打电话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]
Output:
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')