26

Let's say I have a DataFrame like this:

df A B 5 0 1 18 2 3 125 4 5 

where 5, 18, 125 are the index

I'd like to get the line before (or after) a certain index. For instance, I have index 18 (eg. by doing df[df.A==2].index), and I want to get the line before, and I don't know that this line has 5 as an index.

2 sub-questions:

  • How can I get the position of index 18? Something like df.loc[18].get_position() which would return 1 so I could reach the line before with df.iloc[df.loc[18].get_position()-1]
  • Is there another solution, a bit like options -C, -A or -B with grep ?
0

2 Answers 2

39

For your first question:

base = df.index.get_indexer_for((df[df.A == 2].index)) 

or alternatively

base = df.index.get_loc(18) 

To get the surrounding ones:

mask = pd.Index(base).union(pd.Index(base - 1)).union(pd.Index(base + 1)) 

I used Indexes and unions to remove duplicates. You may want to keep them, in which case you can use np.concatenate

Be careful with matches on the very first or last rows :)

Sign up to request clarification or add additional context in comments.

Comments

2

If you need to convert more than 1 index, you can use np.where.

Example:

# df A B 5 0 1 18 2 3 125 4 5 

import pandas as pd import numpy as np df = pd.DataFrame({"A": [0,2,4], "B": [1,3,5]}, index=[5,18,125]) np.where(df.index.isin([18,125])) 

Output:

(array([1, 2]),) 

1 Comment

This is a great trick to get iloc-valid indices after getting "naive" indices from a conditional such as: df[df[col]==value].index.tolist()

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.