我经常有MultiIndex索引,我想迭代更高级别索引相等的组.它基本上看起来像
from random import choice import pandas as pd N = 100 df = pd.DataFrame([choice([1, 2, 3]) for _ in range(N)], columns=["A"], index=pd.MultiIndex.from_tuples([(choice("ab"), choice("cd"), choice("de")) for _ in range(N)])) for idx in zip(df.index.get_level_values(0), df.index.get_level_values(1)): df_select = df.ix[idx]
有没有办法更整洁地进行for循环迭代?
使用groupby
.df_select
视图的索引包括前两个级别值,但在其他方面与您的示例类似.
for idx, df_select in df.groupby(level=[0, 1]): ...