2016-12-18 4 views
2

私は下の表の要約行を持っています。結果は、メンバーID、領収書の合計、および支出の合計のユニークなカウントになります。しかし、私が考えることができる唯一の方法は、同じ値を持つ新しい列を作成し、結果を得るためにgroupby集計関数を実行するために同じ値の列を使用することです。もっと簡単な方法はありますか?要約行またはデータフレーム

import pandas as pd 
df=pd.DataFrame({'Mbr ID':['ID0001','ID0002','ID0003','ID0004'], 
       'Receipts':[3,5,12,5],     
       'Spending':[130,22,313,46], 
       }) 

enter image description here

+0

「df ['Mbr ID']のようなものです.nunique()、df.Rece ipts.sum()、df.Spending.sum() '? – Zero

答えて

2

:1による以前の1つの刻みとして新しい行のindexが同じ必要がある場合は

df.loc['Summary'] = [df['Mbr ID'].nunique(), df.Receipts.sum(), df.Spending.sum()] 
print (df) 
     Mbr ID Receipts Spending 
0  ID0001   3  130 
1  ID0002   5  22 
2  ID0003  12  313 
3  ID0004   5  46 
Summary  4  25  511 

df.loc[df.index[-1] + 1] = [df['Mbr ID'].nunique(), df.Receipts.sum(), df.Spending.sum()] 
print (df) 
    Mbr ID Receipts Spending 
0 ID0001   3  130 
1 ID0002   5  22 
2 ID0003  12  313 
3 ID0004   5  46 
4  4  25  511 
0

ただ、これを行います。

あなたが列 Mbr IDと列 ReceiptsSpendingsumlocnuniqueすることにより、新しい要約行を追加する必要がある
df.groupby('Mbr ID').agg({ 
     'Mbr ID': 'count', 
     'Receipts': 'sum', 
     'Spending': 'sum'}) 

#   Mbr ID Spending Receipts 
# Mbr ID        
# ID0001  1  130   3 
# ID0002  1  22   5 
# ID0003  1  313  12 
# ID0004  1  46   5 
関連する問題