2017-04-06 72 views
3

使用熊貓cut我可以通過提供邊緣和熊貓創建分類箱來定義箱櫃,如(a, b]從熊貓分類中的分類箱

我的問題是如何排序箱(從最低到最高)?

import numpy as np 
import pandas as pd 

y = pd.Series(np.random.randn(100)) 

x1 = pd.Series(np.sign(np.random.randn(100))) 
x2 = pd.cut(pd.Series(np.random.randn(100)), bins = [-3, -0.5, 0, 0.5, 3]) 

model = pd.concat([y, x1, x2], axis = 1, keys = ['Y', 'X1', 'X2']) 

我有一箇中間結果,其中箱的順序被保存

int_output = model.groupby(['X1', 'X2']).mean().unstack() 
int_output.columns = int_output.columns.get_level_values(1) 

X2 (-3, -0.5] (-0.5, 0] (0, 0.5] (0.5, 3] 
X1            
-1.0 0.101475 -0.344419 -0.482992 -0.015179 
1.0 0.249961 0.484757 -0.066383 -0.249414 

但後來我這樣做,隨意改變倉的順序等操作:

output = pd.concat(int_output.to_dict('series'), axis = 1) 

     (-0.5, 0] (-3, -0.5] (0, 0.5] (0.5, 3] 
X1            
-1.0 -0.344419 0.101475 -0.482992 -0.015179 
1.0 0.484757 0.249961 -0.066383 -0.249414 

現在我想繪製條形圖中的數據,但是我希望箱子從最低(-3,-0.5)到最高(0.5,3)排序。

我想我可以通過操縱字符串,使用「,」拆分然後清除括號來實現這一點,但我想知道是否有更好的方法。

+0

我認爲你的問題歸結爲時間間隔被表示爲包含字符串浮動值本身難以分類。將間隔轉換爲python元組怎麼樣?例如'import ast; x2 = x2.map(lambda r:ast.literal_eval(r.replace(']',')')))'。這使得以後很容易對它們進行分類。 – mhoff

回答

2

失敗的主要問題orderedCategoricalIndex

np.random.seed(12456) 
y = pd.Series(np.random.randn(100)) 
x1 = pd.Series(np.sign(np.random.randn(100))) 
x2 = pd.cut(pd.Series(np.random.randn(100)), bins = [-3, -0.5, 0, 0.5, 3]) 

model = pd.concat([y, x1, x2], axis = 1, keys = ['Y', 'X1', 'X2']) 
int_output = model.groupby(['X1', 'X2']).mean().unstack() 
int_output.columns = int_output.columns.get_level_values(1) 

print (int_output) 
X2 (-3, -0.5] (-0.5, 0] (0, 0.5] (0.5, 3] 
X1            
-1.0 0.230060 -0.079266 -0.079834 -0.064455 
1.0 -0.451351 0.268688 0.020091 -0.280218 

print (int_output.columns) 
CategoricalIndex(['(-3, -0.5]', '(-0.5, 0]', '(0, 0.5]', '(0.5, 3]'], 
       categories=['(-3, -0.5]', '(-0.5, 0]', '(0, 0.5]', '(0.5, 3]'], 
       ordered=True, name='X2', dtype='category') 

output = pd.concat(int_output.to_dict('series'), axis = 1) 
print (output) 
     (-0.5, 0] (-3, -0.5] (0, 0.5] (0.5, 3] 
X1            
-1.0 -0.079266 0.230060 -0.079834 -0.064455 
1.0 0.268688 -0.451351 0.020091 -0.280218 

print (output.columns) 
Index(['(-0.5, 0]', '(-3, -0.5]', '(0, 0.5]', '(0.5, 3]'], dtype='object') 

一個可能的解決方案是從output.columnsextract第一號,創建助手系列和排序。最後reindex原始列:

cat = output.columns.str.extract('\((.*),', expand=False).astype(float) 
a = pd.Series(cat, index=output.columns).sort_values() 
print (a) 
(-3, -0.5] -3.0 
(-0.5, 0] -0.5 
(0, 0.5]  0.0 
(0.5, 3]  0.5 
dtype: float64 

output = output.reindex(columns=a.index) 
print (output) 
     (-3, -0.5] (-0.5, 0] (0, 0.5] (0.5, 3] 
X1            
-1.0 0.230060 -0.079266 -0.079834 -0.064455 
1.0 -0.451351 0.268688 0.020091 -0.280218 
0

一個簡單的辦法,以您在上方突出的問題是簡單地重新排序列:

output[sorted(output.columns)]