1

Let's say we getting pandas index as input for a function. Then I need to get the next immediate index from the dataframe based on the index input. The dataframe index can be a string or number. I want to know how to do this.

For example:

index col 1
2342 aaa
2822 bbb
3452 ccc

If the function gets 2342 as input, how to get the immediate next index in the dataframe (2822)? Imagine that the dataframe usually has more than 100k rows. The indexing strategy is out of my control.

Shaido
  • 27,497
  • 23
  • 70
  • 73
  • 1
    If there's no rule _a priori_ on how the index was set, probably the best is just to treat the index as a list and just [look for the position of the target](https://stackoverflow.com/questions/176918/finding-the-index-of-an-item-in-a-list) in it. – Ignatius Reilly Nov 11 '22 at 04:28

1 Answers1

1

You can start by finding the actual row index of the row with the index you want to get. With the example dataframe and 2342 as input, this would be 0. Then simply add 1 to this row index and use iloc. Code:

i = 2342
row_index = df.loc[df['index'] == i].index.item()
df.iloc[row_index + 1, df.columns.get_loc('index')]

The result is 2822.

Shaido
  • 27,497
  • 23
  • 70
  • 73