Nested For Loop to Access MultiIndex Pandas Dataframe
<p>I have a Dataframe with 3 levels of MultiIndex. They are "Category", "Brand" and "Zip Code". There is one series ("Sales") in the Dataframe. I'd like to loop around the "Category" and "Brand" index levels and serve up a Dataframe with "Zip Code" as the Index and "Sales" as a series.</p>

<p>When I only have two multi-index level I have used <code>groupby</code> e.g.</p>

<pre><code>for name, group in df.groupby(level = 0):
</code></pre>

<p>I'm struggling to see how to iterate through the next index level.</p>

<p>Not sure how you want your DataFrame grouped, but I see 2 options. The first option will give you a DataFrame with the zip codes as the index ordered as they currently are within the MultiIndex. The second option will group the zip codes such that you have an index of only the unique zip codes and the sales numbers could be aggregated with whatever function you fancy. These can both be accomplished a couple of ways:</p>

<p>1a)</p>

<pre><code>df = df.reset_index([0,1], drop=True)
</code></pre>

<p>1b)</p>

<pre><code>df.index = df.index.droplevel([0,1])
</code></pre>

<p>2a)</p>

<pre><code>df = df.reset_index([0,1], drop=True).groupby(by='Zip Code')
</code></pre>

<p>2b) </p>

<pre><code>df.index = df.index.droplevel([0,1])
df = df.groupby(by='Zip Code')
</code></pre>

<p>Hope that helps.</p>

python pandas dataframe