Search code examples
pythonpandasargmax

Finding the indexes of the N maximum values across an axis in Pandas


I know that there is a method .argmax() that returns the indexes of the maximum values across an axis.

But what if we want to get the indexes of the 10 highest values across an axis?

How could this be accomplished?

E.g.:

data = pd.DataFrame(np.random.random_sample((50, 40)))

Solution

  • You can use argsort:

    s = pd.Series(np.random.permutation(30))
    sorted_indices = s.argsort()
    top_10 = sorted_indices[sorted_indices < 10]
    print(top_10)
    

    Output:

    3     9
    4     1
    6     0
    8     7
    13    4
    14    2
    15    3
    19    8
    20    5
    24    6
    dtype: int64