Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

define aggfunc with two columns as arguments in pandas pivot table

I want only one value column as a result in below code:

df = pd.DataFrame({'team':['a','a'],'balance':[100,3],'dpd':[0,60]})
df.pivot_table(index='team',values=['balance','dpd'], 
               aggfunc=lambda x: np.sum(np.where(x.dpd>=30,x.balance,0))/np.sum(x.balance))

this return:

      balance      dpd
team 
a    0.029126 0.029126

But, what I want is a column with new name :

        dqratio
team
a       0.029126
like image 775
hyunwoo jeong Avatar asked Nov 08 '22 07:11

hyunwoo jeong


1 Answers

I think you are looking for groupby and apply

df.groupby('team').apply(lambda x: np.sum(np.where(x['dpd']>=30,x['balance'],0))/np.sum(x['balance'])).to_frame('dqratio')
       dqratio
team          
a     0.029126
like image 97
BENY Avatar answered Nov 13 '22 17:11

BENY