How to make a group id using pandas
<p>R's <code>data.table</code> package has a really convenient <code>.GRP</code> method for generating group index values.</p>

<pre><code>library(data.table)
dt &lt;- data.table(
  Grp=c("a", "z", "a", "f", "f"),
  Val=c(3, 2, 1, 2, 2)
)
dt[, GrpIdx := .GRP, by=Grp]

   Grp Val GrpIdx
1:   a   3      1
2:   z   2      2
3:   a   1      1
4:   f   2      3
5:   f   2      3
</code></pre>

<p>What's the best way to accomplish the same thing using <code>pandas</code>?</p>

<pre><code>import pandas as pd
df = pd.DataFrame({'Grp':["a", "z", "a", "f", "f"], 'Val':[3, 2, 1, 2, 2]})
</code></pre>

<p>You could use <a href="http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.Series.rank.html" rel="nofollow"><code>rank</code></a> to identify unique groups with the <code>method</code> arg set to <code>dense</code> which accepts <code>string</code> values:</p>

<pre><code>df['GrpIdx'] = df['Grp'].rank(method='dense').astype(int)
</code></pre>

<p><a href="http://i.stack.imgur.com/9H47r.png" rel="nofollow"><img src="http://i.stack.imgur.com/9H47r.png" alt="Image"></a></p>

python pandas dataframe