2014-04-14 54 views
2

切片功能與多指標熊貓面板

我創建了一個Panel構建體從PandasMultiIndex(見代碼)。如果沒有MultiIndex我可以切片PanelDataFrame方便的命令:切片功能與多指標熊貓面板

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

如果我切片MultiIndexPanel,其結果將是一個Panel。我能做些什麼來獲得DataFrame(切片3D Panel => 2D DataFrame)?爲什麼3D Panel a Panel切片的結果呢?如果可能的話,結果應該是從'2010-01-01'到'2010-01-03'的所有區域('zOne' - 'zFour')的DataFrame

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) 

注:我使用Python v.2.7.6IPython v.1.2.1

回答

1

我想,當你切多指標的熊貓面板中的軸,因爲該指數是MultiIndex,切片後指數仍然存在(在這種情況下Items axis: 2 to 2),因此其結果仍然是一個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) 

所以,如果我們使用MultiIndex切片的方法稍有不同,返回的是一個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] 
+0

謝謝你的快速和合格的答卷。我認爲這是我正在尋找的。 – Spirou