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

Time:11-03

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.

CodePudding user response:

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]
  • Related