How To Iterate Over Multiindex Levels In Pandas?
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 =
Solution 1:
Use groupby
. The index of the df_select
view includes the first two level values, but otherwise is similar to your example.
foridx, df_select in df.groupby(level=[0, 1]):
...
Solution 2:
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:
for idx in df.index.map(lambda x: x[:-1]):
df_select=df.ix[idx]
Post a Comment for "How To Iterate Over Multiindex Levels In Pandas?"