In Python, the pandas library includes built-in functionalities that allow you to perform different tasks with only a few lines of code. One of these functionalities allows you to compute the row number of the nth largest value in a column.
Row number | Column a |
0 | 20 |
1 | 5 |
2 | 12 |
3 | 4 |
4 | 1 |
Row number of 2nd Largest Value in Column a: 2
In this method, we first initialize the pandas
dataframe. Then we use argsort()
, which gives the indices of sorted column of dataframe. Then, we get the row number of the nth largest value from the indices list.
#importing pandas and numpy librariesimport pandas as pdimport numpy as np#initializing pandas dataframedf = pd.DataFrame(np.random.randint(1, 100, 20).reshape(10,-1), columns=list('ab'))#initializing the nth valuen = 5#computing row number of nth largest value in column "b"result = df['b'].argsort()[::-1][n]print(df)print("Row number in b:", result)