pandas get position of a given index in DataFrame

后端 未结 1 692
时光说笑
时光说笑 2020-12-05 11:44

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\'

相关标签:
1条回答
  • 2020-12-05 12:13

    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 :)

    0 讨论(0)
提交回复
热议问题