title: Groupby Apply Custom Function Pandas
body: <p>I'm trying to apply a custom function in pandas similar to the groupby and mutate functionality in dplyr.</p>
  
  <p>What I'm trying to do is say given a pandas dataframe like this:</p>
  
  <pre><code>df = pd.DataFrame({'category1':['a','a','a', 'b', 'b','b'],
    'category2':['a', 'b', 'a', 'b', 'a', 'b'],
    'var1':np.random.randint(0,100,6),
    'var2':np.random.randint(0,100,6)}
  )
  
  df
    category1 category2  var1  var2
  0         a         a    23    59
  1         a         b    54    20
  2         a         a    48    62
  3         b         b    45    76
  4         b         a    60    26
  5         b         b    13    70
  </code></pre>
  
  <p>apply some function that returns the same number of elements as the number of elements in the group by:</p>
  
  <pre><code>def myfunc(s):
    return [np.mean(s)] * len(s)
  </code></pre>
  
  <p>to get this result</p>
  
  <pre><code>df
    category1 category2  var1  var2   var3
  0         a         a    23    59   35.5
  1         a         b    54    20   54
  2         a         a    48    62   35.5
  3         b         b    45    76   29
  4         b         a    60    26   60
  5         b         b    13    70   29
  </code></pre>
  
  <p>I was thinking of something along the lines of:</p>
  
  <pre><code>df['var3'] = df.groupby(['category1', 'category2'], group_keys=False).apply(lambda x: myfunc(x.var1))
  </code></pre>
  
  <p>but haven't been able to get the index to match.</p>
  
  <p>In R with dplyr this would be</p>
  
  <pre><code>df &lt;- df %&gt;%
    group_by(category1, category2) %&gt;%
    mutate(
      var3 = myfunc(var1)
    )
  </code></pre>
  
  <p>So I was able to solve it by using a custom function like:</p>
  
  <pre><code>def myfunc_data(data):
  
    data['var3'] = myfunc(data.var1)
    return data
  </code></pre>
  
  <p>and</p>
  
  <pre><code>df = df.groupby(['category1', 'category2']).apply(myfunc_data)
  </code></pre>
  
  <p>but I guess I was still wondering if there's a way to do it without defining this custom function.</p>