title: Python PANDAS: Groupby Transform Sum Unique
body: <p>I have a situation where I am creating a pivot table in PANDAS where it makes more sense to calculate the fields separately and just use .pivot_table() for the pivot step.  However, I am running into some difficultly trying to calculate the denominator for my percentages.  Essentially, due to the data format I appear to need to do something like "groupby transform unique sum" on the second line below (which is where I am stuck):</p>
  
  <pre><code>df['numerator'] = df.groupby(['category1','category2'])['customer_id'].transform('nunique')
  df['denominator'] =  df.groupby(['category2'])['numerator'].nunique().transform('sum')
  df['percentage'] = (df['numerator'] / df['denominator'])
  
  df_pivot  = df.pivot_table(index='category1',
                             columns=['category2'],
                             values=['numerator','percentage']) \
                             swaplevel(0,1,axis=1)
  
  df_pivot.loc['total', :] = df_pivot.sum().values
  </code></pre>
  
  <p>My apologies for not being able to provide any dummy data, but I would appreciate any tips if I have hopefully provided enough detail to reason about.</p>