lambda function inside pivot table

34 views Asked by At

Hi my dataset is arranged like this:

enter image description here i want to calculate average scores of students arranged againsts state/district like in pivot table

i used the following code

    piv = pd.pivot_table(df, 
                     index=['State', 'District'], 
                     columns='Round', values=['Marks'], 
                     aggfunc=lambda x: ((sum(x)/df['Unique_Key'].nunique())/df['Question'].nunique())*100, 
                     margins=True, 
                     margins_name='All')

    piv

but it is passing df['Unique_Key'].nunique())and df['Question'].nunique() for the whole dataset. Instead it should take Unique_Key counts (distinct) and Question counts (distinct) for each district/state like we do in DAX excel. How to do it? How to pass columns references within pivot table?

0

There are 0 answers