How to get the index value of the row above and below in Pandas idxmax()

Question:

I have the following code:

import pandas as pd
df = pd.util.testing.makeDataFrame()
max_index = df.A.idxmax()

What I am trying to do is get the index value right above and below max_index in the dataframe. Could you please advise how this could be accomplished.

Asked By: Slartibartfast

||

Answers:

If you’re unsure whether the index has duplicates, a safe way is:

import pandas as pd
df = pd.util.testing.makeDataFrame()
max_index = df.A.idxmax()
before = df['A'].shift(-1).idxmax()
after = df['A'].shift().idxmax()

If the indices are unique:

i = df.index.get_loc(max_index)
before, after = df.index[i-1], df.index[i+1]

Or, maybe slightly more efficient and which also handles duplicated indices:

i = df.reset_index()['A'].idxmax()
before, max_index, after = df.index[i-1:i+2]
Answered By: mozway
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.