如何在 Pandas 中迭代 MultiIndex 级别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34139121/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to iterate over MultiIndex levels in Pandas?
提问by Gerenuk
I often have MultiIndex indices and I'd like to iterate over groups where higher level indices are equal. It basically looks like
我经常有 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]
Is there a way to do the for loop iteration more neatly?
有没有办法更巧妙地进行for循环迭代?
回答by Mzzzzzz
回答by rstreppa
Alternatively to groupby logic you can use a lambda function, which has the advantage of not having to specify the number of levels, i.e. it will pick all levels except the very last one:
作为 groupby 逻辑的替代方案,您可以使用 lambda 函数,它的优点是不必指定级别数,即它将选择除最后一个级别之外的所有级别:
for idx in df.index.map(lambda x: x[:-1]):
df_select=df.ix[idx]