2017-11-13 16 views
1

パンダでは、groupby-apply操作を実行し、それぞれの 'groupby'オブジェクトを見ると、グループ化インデックスは保持されます。パンダGroupby-Applyでグループ化インデックスを含まない方法

>>> df = pd.DataFrame({'gender':['M','M','F','F','F','M'],'age':[10,10,20,20,30,30],'income':[10000,15000,20000,25000,30000,35000],'education':[0,1,2,2,2,3]}) 
>>> df 
    age education gender income 
0 10   0  M 10000 
1 10   1  M 15000 
2 20   2  F 20000 
3 20   2  F 25000 
4 30   2  F 30000 
5 30   3  M 35000 
>>> df.groupby(['age','education']).apply(lambda x:x.iloc[np.argmax(x['income'].values),:]) 
       age education gender income 
age education 
10 0   10   0  M 10000 
    1   10   1  M 15000 
20 2   20   2  F 25000 
30 2   30   2  F 30000 
    3   30   3  M 35000 

['age','education']は、返品のインデックスと値の両方に表示されます。これは私にとっては冗長であり、使い勝手が悪いです。 'groupby'オブジェクトにグループ化インデックスを含めない方法はありますか?例えば、次のようなものを得るには:

   gender income 
age education 
10 0   M  10000 
    1   M  15000 
20 2   F  25000 
30 2   F  30000 
    3   M  35000 

P.S.私はdropindex()と呼ぶことができますが、よりクリーンな方法があるかどうかを知りたいのであれば、グループ化されたオブジェクトにグループ化インデックスを保持する理由があります。私はRの世界からPythonに来て、Rのdata.tableでは、簡潔な方法で同じ操作を行うことができますdt[,.SD[which.max(income)],by=.(age,education)]

答えて

0

groupbyの構文はちょっと大変です。しかし、あなたが最大収入の指標を見つけてそれをdfにインデックスするのであれば、少しクリーナーです:

In [46]: df.groupby(['age','education'])['income'].idxmax() 
Out[46]: 
age education 
10 0   0 
    1   1 
20 2   3 
30 2   4 
    3   5 
Name: income, dtype: int64 

In [47]: df.loc[df.groupby(['age','education'])['income'].idxmax()] 
Out[47]: 
    age education gender income 
0 10   0  M 10000 
1 10   1  M 15000 
3 20   2  F 25000 
4 30   2  F 30000 
5 30   3  M 35000 
+0

ありがとうございました。これは手元の特定の問題では機能しますが、各グループのグループ化インデックスを無効にするapply()関数の切り替えがあるのでしょうか?だから、それはagg()のように振る舞う? – Bill

関連する問題