2014-11-04 94 views
2

我遇到了熊貓樞軸功能的麻煩。我試圖按月份和年度調整銷售數據。該數據集如下:熊貓數據透視表按字母順序排列分類數據(錯誤地)當添加列參數

Customer - Sales - Month Name - Year 
a  - 100 - january  - 2013 
a  - 120 - january  - 2014 
b  - 220 - january  - 2013 

爲了月份名稱排序正確我添加了一個列與月的名稱作爲分類數據。

dataset['Month'] = dataset['Month Name'].astype('category') 
dataset['Month'].cat.set_categories(['January', 'February', 'March', 'April', 'May', 'June',  'July', 'August', 'September', 'October', 'November', 'December'],inplace=True) 
dataset.pop('Month Name') 

當我使用功能:

pt = dataset.pivot_table(values="Sales", index="Month") 

我得到預期的結果

Month 
January  3620302.79 
February  3775507.25 
March  4543839.69 

然而,當我遇到年月轉動月份按字母順序排序。

print dataset.pivot_table(values='Sales', index="Month", columns="Year", aggfunc="sum") 
Year   2011  2012  2013  2014 
Month             
April  833692.19 954483.28 1210847.85 1210926.61 
August  722604.75 735078.52 879905.23 1207211.00 
December 779873.51 1053441.71 1243745.73   NaN 

我很感激任何幫助正確排序上個代碼示例中的月份名稱。

感謝,

弗蘭克

+0

所以,結果是指數''object'' D類,作爲它的由自動轉換關鍵點,它不會按照c進行重新排序ategory。所以這是一個錯誤;熊貓還不支持CategoricalIndex,因爲這將是理想的結果。這裏是錯誤報告:https://github.com/pydata/pandas/issues/8731 – Jeff 2014-11-04 21:55:49

+0

@Frank,我提供了一個答案,你有沒有回顧? – Anzel 2014-11-09 20:33:41

+0

當我在類別列中使用pivot_table並且該類別在DataFrame中沒有值時,我遇到了類似問題pandas sais無法將NA轉換爲整數 – Diego 2015-04-28 19:46:48

回答

0

pivot_table之後它會重新索引「月」,因此按字母順序排序。幸運的是,您總是可以將您的dataset['Month']轉換爲pandas.datetime,並在pivot_table的reindex之後將其轉換回字符串。

不是最好的解決方法,但這應該做的伎倆(我用一些隨機的假人):

import pandas as pd 
... 
# convert dataset['Month'] to pandas.datetime by the time of pivot 
# it will reindex by datetime hence the sort order is kept 
pivoted = dataset.pivot_table(index=pd.to_datetime(dataset['Month']), columns='Year', \ 
           values='Sales', aggfunc='sum') 
pivoted 
Year  2012 2013 2014 
Month      
2014-01-04 151 295 NaN 
2014-02-04 279 128 NaN 
2014-03-04 218 244 NaN 
2014-04-04 274 152 NaN 
2014-05-04 276 NaN 138 
2014-06-04 223 NaN 209 
... 

# then re-set the index back to Month string, "%B" means month string "January" etc. 
pivoted.index = [pd.datetime.strftime(m, format='%B') for m in pivoted.index] 

pivoted 
Year  2012 2013 2014 
January  151 295 NaN 
February 279 128 NaN 
March  218 244 NaN 
April  274 152 NaN 
May   276 NaN 138 
June  223 NaN 209 
... 

但是你會錯過的「月」索引標籤,如果你需要,你可以複製數據集[「月」]到另一列(稱之爲M),並轉換爲datetime,然後設置多個索引上pivot_table像:

dataset.pivot_table(index=['M', 'Month'], ...) 
+0

如果它不是日期?如何在pivot_table之後保留索引的原始順序? – Cesar 2015-06-09 21:44:23

+0

@Cesar,如果它不是一個日期,你可以有一個自定義字典映射像'{'one':1,'two':2,'three':3,...}'這樣的順序,那麼它只是一個將索引映射到* sorting *的值,然後將它們重新映射回有意義的鍵。就目前而言,確實有更好的解決方案,但它符合OP要求的。 – Anzel 2015-06-09 22:35:17