2016-05-12 6 views
0

とレベルのカテゴリーごとにすべてしかし、中央値を置き換えます。パンダは、次のピボットテーブルを考えると空白

df=pd.DataFrame({'A':['a','a','a','a','a','b','b','b','b'], 
       'B':['x','y','z','x','y','z','x','y','z'], 
       'C':['a','b','a','b','a','b','a','b','a'], 
       'D':[7,5,3,4,1,6,5,3,1]}) 
table = pd.pivot_table(df, index=['A', 'B','C'],aggfunc='sum') 
table 

      D 
A B C 
a x a 7 
     b 4 
    y a 1 
     b 5 
    z a 3 
b x a 5 
    y b 3 
    z a 1 
     b 6 

を、私は、各レベルlike soの値にアクセスできることを知っている:

In [128]:  
table.index.get_level_values('B') 

Out[128]: 
Index(['x', 'x', 'y', 'y', 'z', 'x', 'y', 'z', 'z'], dtype='object', name='B') 

In [129]: 
table.index.get_level_values('A') 

Out[129]: 
Index(['a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'b'], dtype='object', name='A') 

次私は中間レベルまたはn/2 + 1の値を空白( '')で保存して、各外部レベルのすべての値を置き換えたいと思います。

だから:

Index(['x', 'x', 'y', 'y', 'z', 'x', 'y', 'z', 'z'], dtype='object', name='B') 

は次のようになります。

Index(['x', '', 'y', '', 'z', 'x', 'y', 'z', ''], dtype='object', name='B') 

​​

は次のようになります。

Index(['', '', 'a', '', '', '', 'b', '', ''], dtype='object', name='A') 

は、最終的に(私のラベルの一部がシフトアップするかもしれませんが)、私はこのような何かチャート、matplotlibの水平バーでの二次および三次y軸ラベルとしてこれらを使用しようとします。 enter image description here

答えて

0

は最後まで時間がかかりましたこれを把握してください...

#First, get the values of the index level. 
A=table.index.get_level_values(0) 

#Next, convert the values to a data frame. 
ndf = pd.DataFrame({'A2':A.values}) 

#Next, get the count of rows per group. 
ndf['A2Count']=ndf.groupby('A2')['A2'].transform(lambda x: x.count()) 

#Next, get the position based on the logic in the question. 
ndf['A2Pos']=ndf['A2Count'].apply(lambda x: x/2 if x%2==0 else (x+1)/2) 

#Next, order the rows per group. 
ndf['A2GpOrdr']=ndf.groupby('A2').cumcount()+1 

#And finally, create the column to use for plotting this level's axis label. 
ndf['A2New']=ndf.apply(lambda x: x['A2'] if x['A2GpOrdr']==x['A2Pos'] else "",axis=1) 
ndf 

    A2 A2Count A2Pos A2GpOrdr A2New 
0 a 5  3.0  1  
1 a 5  3.0  2  
2 a 5  3.0  3  a 
3 a 5  3.0  4  
4 a 5  3.0  5  
5 b 4  2.0  1  
6 b 4  2.0  2  b 
7 b 4  2.0  3  
8 b 4  2.0  4  
関連する問題