title: Python Pandas aggregation with condition
body: <p>I need to group my dataframe and use several aggregation functions on different columns. And some of this aggregation have conditions.</p>
  
  <p>Here is an example. The data are all the orders from 2 customers and I would like to calculate some information on each customer. Like their orders count, their total spendings and average spendings.</p>
  
  <pre><code>import pandas as pd
  
  data = {'order_id' : range(1,9),
          'cust_id' : [1]*5 + [2]*3,
          'order_amount' : [100,50,70,75,80,105,30,20],
          'cust_days_since_reg' : [0,10,25,37,52,0,17,40]}
  
  orders = pd.DataFrame(data)
  
  aggregation = {'order_id' : 'count',
                 'order_amount' : ['sum', 'mean']}
  
  cust = orders.groupby('cust_id').agg(aggregation).reset_index()
  cust.columns = ['_'.join(col) for col in cust.columns.values]
  </code></pre>
  
  <p>This works fine and gives me :</p>
  
  <p><a href="https://i.stack.imgur.com/yjFyc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yjFyc.png" alt="enter image description here"></a>
  _</p>
  
  <p>But I have to add an aggregation function with a argument and a condition : the amount a customer spent in his first X months (X must be customizable)</p>
  
  <p>Since I need an argument in this aggregation I tried :</p>
  
  <pre><code>def spendings_X_month(group, n_months):
      return group.loc[group['cust_days_since_reg'] &lt;= n_months*30, 
                       'order_amount'].sum()
  
  aggregation = {'order_id' : 'count',
                 'order_amount' : ['sum',
                                   'mean',
                                   lambda x: spendings_X_month(x, 1)]}
  
  cust = orders.groupby('cust_id').agg(aggregation).reset_index()
  </code></pre>
  
  <p>But that last line gets me the error : <code>KeyError: 'cust_days_since_reg'</code>.
  It must be a scoping error, the <code>cust_days_since_reg</code> column must not be visible in this situation.</p>
  
  <p>I could calculate this last column separately and then join the resulting dataframe to the first but there must be a better solution, that makes every thing in only one groupby.</p>
  
  <p>Could anyone help me with this problem please ?</p>
  
  <p>Thank You</p>