Pandas DENSE RANK
<p>I'm dealing with pandas dataframe and have a frame like this:</p>

<pre><code>Year Value  
2012  10
2013  20
2013  25
2014  30
</code></pre>

<p>I want to make an equialent to DENSE_RANK () over (order by year) function. to make an additional column like this:</p>

<pre><code>    Year Value Rank
    2012  10    1
    2013  20    2
    2013  25    2
    2014  30    3
</code></pre>

<p>How can it be done in pandas?</p>

<p>Thanks!</p>

<p>The fastest solution is <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.factorize.html" rel="nofollow"><code>factorize</code></a>:</p>

<pre><code>df['Rank'] = pd.factorize(df.Year)[0] + 1
</code></pre>

<p><strong>Timings</strong>:</p>

<pre><code>#len(df)=40k
df = pd.concat([df]*10000).reset_index(drop=True)

In [13]: %timeit df['Rank'] = df.Year.rank(method='dense').astype(int)
1000 loops, best of 3: 1.55 ms per loop

In [14]: %timeit df['Rank1'] = df.Year.astype('category').cat.codes + 1
1000 loops, best of 3: 1.22 ms per loop

In [15]: %timeit df['Rank2'] = pd.factorize(df.Year)[0] + 1
1000 loops, best of 3: 737 Âµs per loop
</code></pre>

python sql pandas