如何在 pandas 中遍历MultiIndex级别? [英] How to iterate over MultiIndex levels in Pandas?
本文介绍了如何在 pandas 中遍历MultiIndex级别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我经常有MultiIndex索引,我想遍历更高级别索引相等的组.基本上看起来像
I often have MultiIndex indices and I'd like to iterate over groups where higher level indices are equal. It basically looks like
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循环迭代?
Is there a way to do the for loop iteration more neatly?
推荐答案
使用 groupby
. df_select
视图的索引包括前两个级别的值,但是与您的示例相似.
Use groupby
. The index of the df_select
view includes the first two level values, but otherwise is similar to your example.
for idx, df_select in df.groupby(level=[0, 1]):
...
这篇关于如何在 pandas 中遍历MultiIndex级别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文