2017-06-03 57 views
3

計算從透視表中最大的我已經寫代碼來計算特點3 GROUPBY特徵1的數量和特徵如何在python

pd.pivot_table(data=train, index=['feature1', 'feature2'], values=['feature3'], aggfunc='count') 

誰的輸出是:

feature1 feature2 feature3 
129001 0 4 
     1 10 
     2 11 
     3 22 
     4 26 
     5 38 
129002 0 6 
     2 45 
     5 25 

現在我想計算最大特點3 GROUPBY的優點1

feature1 feature3 
129001 38 
129002 45 
+0

您可以編輯澄清數據的問題? –

+0

你需要澄清什麼? –

+0

很多,建議您檢查如何[提出好問題](http://stackoverflow.com/help/how-to-ask),其中包括創建[最小,完整和可驗證](http:// stackoverflow。 com/help/mcve)例子。 –

回答

2

IIUC:

你需要下面的語句:

df.groupby(level=0)['feature3'].max() 

先從你pivot_table

print(df) 
        feature3 
feature1 feature2   
129001 0    4 
     1    10 
     2    11 
     3    22 
     4    26 
     5    38 
129002 0    6 
     2    45 
     5    25 

groupby結果用食指的level 0max

df.groupby(level=0)['feature3'].max() 

輸出:

feature1 
129001 38 
129002 45 
Name: feature3, dtype: int64 
2

你可以這樣來做:

In [21]: df 
Out[21]: 
        feature3 
feature1 feature2 
129001 0    4 
     1    10 
     2    11 
     3    22 
     4    26 
     5    38 
129002 0    6 
     2    45 
     5    25 

In [22]: df.max(level='feature1') 
Out[22]: 
      feature3 
feature1 
129001   38 
129002   45 
+0

我喜歡這種方式。 –

+0

@ScottBoston,謝謝:) – MaxU