2014-04-14 148 views
3

我使用pandas melt和groupby使用值和變量創建了以下數據框。我使用以下內容:dataframe熊貓中的總數百分比

df2 = pd.melt(df1).groupby(['value','variable'])['variable']。count()。unstack('variable')。fillna(0 )

  Percentile  Percentile1  Percentile2  Percentile3 
value            
None   0    16    32    48 
bottom  0    69    85    88 
top   0    69    88    82 
mediocre  414   260    209    196 

我期待創造排除了「無」行,並創建「底部」,「頂」的總和的百分比,和「平庸」的行輸出。慾望輸出將如下。

  Percentile  Percentile1  Percentile2  Percentile3 
value            
bottom  0%   17.3%    22.3%    24.0%  
top   0%   17.3%    23.0%    22.4%  
mediocre  414%   65.3%    54.7%    53.6% 

我正在努力的一個主要部分是創建一個新的行來等於輸出。任何幫助將不勝感激!

回答

10

您可以刪除'None'行是這樣的:

df2 = df2.drop('None') 

如果你不希望它永久下降,你不必是結果分配回 df2

然後你得到你想要的輸出:

df2.apply(lambda c: c/c.sum() * 100, axis=0) 
Out[11]: 
      Percentile1 Percentile2 Percentile3 
value           
bottom  17.336683 22.251309 24.043716 
top   17.336683 23.036649 22.404372 
mediocre 65.326633 54.712042 53.551913 

只得到直奔那結果不會永久掉落None行:

df2.drop('None').apply(lambda c: c/c.sum() * 100, axis=0) 
+3

無需通過'apply'去; '100 * df2/df2.sum()'應該可以工作。 – DSM