How to "flatten" a Panda Panel by summing up specific columns
<p>I am still familairizing myself with Pandas, and Python in general, so please excuse if this is a simple question.  I'd also like to avoid one liners so I can understand the underlying actions if possible! :)</p>

<p>I've managed to pull data data which results in a Panel, with four items.  The key of each item is a calendar quarter:</p>

<pre><code>Item '2015-03-31':
Type        Quarterly Sales        Ending Inventory
Shoes       123,456                50,000
Purses      33,222                 10,000

Item '2015-06-30':
Type        Quarterly Sales        Ending Inventory
Shoes       12,744                 56,000
Purses      15,123                 9,000

Item '2015-9-30':
Type        Quarterly Sales        Ending Inventory
Shoes       15,998                 35,000
Purses      11,222                 15,000

Item '2015-12-31':
Type        Quarterly Sales        Ending Inventory
Shoes       12,000                 45,000
Purses      9,551                  7,000
</code></pre>

<p>Ultimately, I would like to "flatten" this by summing up the <strong>Quarterly Sales</strong>, but taking the <strong>Type</strong> and <strong>Ending Inventory</strong> from the most recent entry, and have this in a DataFrame.  So my ending DataFrame would be something like this:</p>

<pre><code>Type        Quarterly Sales        Ending Inventory
Shoes       164,198                45,000
Purses      69,118                 7,000
</code></pre>

<p>I tried using a function such as grouby (e.g. <code>mypanel.groupby('Type').sum()</code>), but that ended up summing both <strong>Quarterly Sales</strong> <em>and</em> <strong>Ending Inventory</strong>, whereas I want to take the "most recent" <strong>Ending Inventory</strong> instead.  An easy "fix" for this would be to take the resulting DataFrame, and then subtract out the summation of the first three quarters for the <strong>Ending Inventory</strong> column, but that seems incredibly awkward.</p>

<p>Any suggestions?</p>

<p>Thanks!</p>

<pre><code>agg_dict = {'Quarterly Sales': 'sum', 'Ending Inventory': 'last'}
pnl.to_frame().T.stack(0).groupby(level='Type').agg(agg_dict)
</code></pre>

<p><a href="http://i.stack.imgur.com/ztaiy.png" rel="nofollow"><img src="http://i.stack.imgur.com/ztaiy.png" alt="enter image description here"></a></p>

python pandas