From sql to pandas: how to create variables from pd.NamedAgg() function

Viewed 33

I would like to calculate this variable, taken from a sql query:

select
STDEV(x + y) AS var1,
1 - (SUM(x)/SUM(y)) AS var2
from df
group by id

with this pandas function:

tab = df.groupby(['id'], as_index=False) \
                               .agg(var1 = pd.NamedAgg(column = , aggfunc= ), 
                                    var2 = pd.NamedAgg(column = , aggfunc= ))        

Can you help me?

Thanks

1 Answers

First create helper column z first and then aggregate std:

d = {'x':[1,2,0.23,0.78], 'y':[0.8,0.6,0.4,1], 'id':list('aabb')}
df = pd.DataFrame(d)

tab = (df.assign(z = df.x + df.y)
        .groupby(['id'], as_index=False)
         .agg(z = pd.NamedAgg(column = 'z', aggfunc='std' )))

print (tab)
  id         z
0  a  0.565685
1  b  0.813173
    
Related