Home >Database >Mysql Tutorial >How Does Pandas' `rank()` Function Implement Dense Ranking?

How Does Pandas' `rank()` Function Implement Dense Ranking?

Barbara Streisand
Barbara StreisandOriginal
2025-01-12 07:26:43219browse

How Does Pandas' `rank()` Function Implement Dense Ranking?

DENSE RANK function in Pandas

The DENSE_RANK() function in Pandas is used to calculate the rank of each row in the data frame, assigning the same rank to the same value. To implement this functionality we can use the pd.Series.rank method and set method='dense'.

Let us consider the following data frame:

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

To create an additional column "Rank" containing dense ranking, we can use the following code:

<code>df['Rank'] = df.Year.rank(method='dense').astype(int)</code>

The resulting data frame is as follows:

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

In this output, the duplicate values ​​from 2013 are all assigned a rank of 2, demonstrating the behavior of dense ranking.

The above is the detailed content of How Does Pandas' `rank()` Function Implement Dense Ranking?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn