Question

Slice Function with a MultiIndex Pandas Panel

I created a Panel construct from Pandas with a MultiIndex (see code). Without MultiIndex I can slice the Panel to a DataFrame with easy commands:

PanelData.major_xs('A')
PanelData.minor_xs('zTwo')

If I slice the MultiIndex Panel, the result will be a Panel. What can I do to get a DataFrame back (Slice a 3D Panel => 2D DataFrame)? Why is the Result of a Slice with a 3D Panel a Panel too? If that is possible, the result should be a DataFrame from '2010-01-01' to '2010-01-03' with all zones ('zOne' - 'zFour').

import pandas as pd

ListLetter = ['A', 'B', 'C', 'D']
ListCode = [2, 1, 1, 0]
ListZone = ['zOne', 'zTwo', 'zThree', 'zFour']
ListRegion = ['USA', 'CH', 'NZ', 'CH']
index = pd.MultiIndex.from_arrays([ListLetter, ListCode], names=['letter', 'code'])
columns =  pd.MultiIndex.from_arrays([ListZone, ListRegion], names=['zone', 'region'])

PanelData = pd.Panel({'2010-01-01': pd.DataFrame(index=index, columns=columns)})
PanelData['2010-01-02'] = pd.DataFrame(index=index, columns=columns)
PanelData['2010-01-03'] = pd.DataFrame(index=index, columns=columns)
PanelData

PanelData:

<class 'pandas.core.panel.Panel'>
Dimensions: 3 (items) x 4 (major_axis) x 4 (minor_axis)
Items axis: 2010-01-01 to 2010-01-03
Major_axis axis: (A, 2) to (D, 0)
Minor_axis axis: (zOne, USA) to (zFour, CH)

NOTE: I'm using Python v.2.7.6 and IPython v.1.2.1.

Was it helpful?

Solution

I think, when you slice an axis of MultiIndex in a Pandas Panel, because the index is MultiIndex, after slicing the index is still there (in this case Items axis: 2 to 2), therefore the result is still a Panel

In [67]:

PanelData.swapaxes(0,1).xs('A', 0)
Out[67]:
<class 'pandas.core.panel.Panel'>
Dimensions: 1 (items) x 3 (major_axis) x 4 (minor_axis)
Items axis: 2 to 2
Major_axis axis: 2010-01-01 to 2010-01-03
Minor_axis axis: (zOne, USA) to (zFour, CH)

So if we use a slightly different method of MultiIndex slicing, the return is a DataFrame

In [68]:

print PanelData.swapaxes(0,1).loc[('A',2),]
zone       zOne zTwo zThree zFour
region      USA   CH     NZ    CH
2010-01-01  NaN  NaN    NaN   NaN
2010-01-02  NaN  NaN    NaN   NaN
2010-01-03  NaN  NaN    NaN   NaN

[3 rows x 4 columns]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top