title: Pandas equivalent to data.table
body: <p>With <code>R</code>'s <em><code>data.table</code></em>, you can perform an operation on a column by group that returns a vector with arbitrary length.</p>
  
  <p>Suppose, I'd like to gather the top 5 values of one column, grouped by another. <em><code>data.table</code></em> takes care of gluing the subgroups together.</p>
  
  <pre><code>require(magrittr)
  library(data.table)
  
  n &lt;- 100
  DT &lt;- data.table(A = rnorm(n), B = sample(letters[1:4], n, replace = TRUE))
  DT[, sort(B, decreasing = TRUE) %&gt;% head(5), by = B]
  </code></pre>
  
  <p>With <code>Python</code> and <em><code>pandas</code></em>, I tried different strategies:</p>
  
  <pre><code>import pandas as pd
  import random
  
  n = 100
  df = pd.DataFrame({'A' : np.random.randn(n), 
                     'B' : [random.choice(list('abc')) for i in range(n)]})
  # first try : 
  groups = df.groupby('B')
  groups.apply(lambda x : sorted(x['A'], reverse=False)[:5])
  </code></pre>
  
  <p>but this solution gives back a 3x1 (assuming I have 3 groups) DataFrame with lists inside the rows, which does not appear weird though, as sorted will give back a list object.</p>
  
  <pre><code># second try:
  groups.apply(lambda x : np.sort(x['A'])[-5:])
  </code></pre>
  
  <p>is no more conclusive.</p>
  
  <p>The solution I found, but looks really verbose to me, imply iterating the groups:</p>
  
  <pre><code>dfs = []
  for g in groups:
      dfs.append(g[1].sort_values('A').tail(5))
  pd.concat(dfs).sort_values('B')
  </code></pre>
  
  <p>Any idea of what I could use as a more elegant way to perform this operation ?
  Thanks, I keep on searching for a Pythonic solution...</p>