2015-09-14 76 views
1

當我嘗試在它下面的例子來過濾熊貓數據幀,如能正常工作:過濾大熊貓pivot_table結果

print data[data['ProductCategory'].isin(['ProductA'])] 

但是當我嘗試做同樣對得到的數據透視表:

pivot = pandas.pivot_table(
     data,index=['ProductCategory', 'Currency', 'Producer'], 
     values=['Price','Quantity','FxRate'], 
     aggfunc={'Price': np.sum, 'Quantity': np.sum,'FxRate': np.mean}) 

print pivot[pivot['ProductCategory'].isin(['ProductA'])] 

我得到一個關鍵的錯誤:數據透視表的

File "pandas\index.pyx", line 134, in pandas.index.IndexEngine.get_loc (pandas\index.c:3838) File "pandas\index.pyx", line 154, in pandas.index.IndexEngine.get_loc (pandas\index.c:3718) File "pandas\hashtable.pyx", line 686, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12294) File "pandas\hashtable.pyx", line 694, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12245) KeyError: 'ProductCategory'

在說明()給出了這樣的:

 FxRate   Price  Quantity 
count 48.00   48.00   48.00 
mean  0.93 4,717,051.34 46,446,338.82 
std  0.20 20,603,134.35 188,008,495.83 
min  0.64 -16,088,043.02 -137,804,378.35 
25%  0.73  -87,306.39   83.75 
50%  1.00  41,198.26  682,025.97 
75%  1.00 2,999,491.53 7,489,198.82 
max  1.25 137,804,362.15 939,610,000.00 

甲pivot.info()給出以下輸出:

<class 'pandas.core.frame.DataFrame'> 
MultiIndex: 48 entries, (ProductA, ProductB, ProductC) to (ProducerA, ProducerB, ProducerC) 
Data columns (total 3 columns): 
FxRate   48 non-null float64 
Price   48 non-null float64 
Quantity  48 non-null float64 
dtypes: float64(3) 

memory usage: 2.3+ KB 
None 

而一個pivot.head()給出了這樣的:

          FxRate  Price Quantity 
ProductCategory Currency  Producer         
ProductA  EUR   ProducterA 1.00  0.90  1.10 
           ProducterB 1.00  0.90  1.10 
       GBP   ProducterB 1.25  1.12  1.37 
ProductB  EUR   ProducterA 1.00  0.90  1.10 
       GBP   ProducterC 1.25  1.12  1.37 
+1

錯誤看起來像「產品分類」是不是列,它看起來像你將其設置爲索引,則可以顯示什麼您的數據透視表看起來像 – EdChum

+0

我將pivot.describe()的輸出添加到問題 –

+2

這告訴我什麼,顯示'pivot.info()'顯示什麼,也許'pivot.head()' – EdChum

回答

1

ProductCategoryCurrency,和Producer現在部分指數在groupby之後操作。嘗試重置名爲pivot.reset_index(inplace=True)的DataFrame索引,然後使用loc照常進行選擇。

>>> pivot[pivot['ProductCategory'].isin(['ProductA'])] 
    ProductCategory Currency Producer FxRate Price Quantity 
0  ProductA  EUR ProducterA 1.00 0.90  1.10 
1  ProductA  EUR ProducterB 1.00 0.90  1.10 
2  ProductA  GBP ProducterB 1.25 1.12  1.37 

如果需要,您可以重置結果的索引。

或者,你可以只使用loc原始pivot如下:

>>> pivot.loc['ProductA'] 
        FxRate Price Quantity 
Currency Producer       
EUR  ProducterA 1.00 0.90  1.10 
     ProducterB 1.00 0.90  1.10 
GBP  ProducterB 1.25 1.12  1.37