title: Pandas - Writing a re-usable Python function to aggregate and calculate weighted average
body: <p>I have a dataframe, for which I could calculate the weighted mean grouped by a given column.</p>
  <p>I would do it like this</p>
  <pre><code># Weighted mean by notional
  def wn(x):
      y = x.copy().dropna()
      if y.empty:
          return np.nan
      else:
          return np.average(y, weights=trade_basket.loc[y.index, 'NotionalTraded'])
  
  
  trading_summary_table_avg = trade_basket[columns_to_wn_avg].groupby(trade_basket.Side).agg(wn)
   
  </code></pre>
  <p>However, I'm trying to make this transformation into a function that would take a <strong>dataframe</strong>, a <strong>list of columns to calculate</strong>, the <strong>weights</strong>, and the <strong>column to aggregate by</strong> and return the result... because I will later have to calculate again the weighted mean, aggregating by different columns, using a different col as the weight, etc... without having to create a new function as above or a lambda</p>
  <p>I'm having a hard time making this into a function because I can't find a way to pass those arguments into my function.</p>
  <p><strong>EDIT</strong></p>
  <p>I ended up doing the below:</p>
  <pre><code>def calc_weighted_avg(basket, weight_col, used_col, agg_col):
      # Weighted mean by weight_col
      def wn(x):
          y = x.copy().dropna()
          if y.empty:
              return np.nan
          else:
              return np.average(y, weights=basket.loc[y.index, weight_col])
  
      weight_avg_table = basket[used_col].groupby(basket[agg_col]).agg(wn)
      return weight_avg_table
  </code></pre>