Search code examples
pandaspandas-groupbysklearn-pandaspandas-datareader

How to fetch next 5 records based on given index in pandas Dataframe


I want to fetch the next 5 records after the specific index.

For example, this is my dataframe:

    Id  Name        code
    1   java         45
    2   python       78
    3   c            65
    4   c++          25
    5   html         74
    6   css          63
    7   javascript   45 
    8   php          44
    9   Ajax         88
    10  jQuery       92

When i provide the index value as 3 then the code must fetch the next 5 values from 3. So the result should look like:

   Id  Name        code
    3   c            65
    4   c++          25
    5   html         74
    6   css          63
    7   javascript   45 

I do not understand how to do this. My code is not working as I want it to.

I am using this code for fetching the next 5 records:

data = df.iloc[df.index.get_loc(indexid):+5]

Solution

  • I would do:

    idx = df.reset_index()['Id'].eq(8).idxmax()
    ranges = np.r_[idx:idx+5] % len(df)
    
    df.iloc[ranges]
    

    Output:

       Id    Name  code
    7   8     php    44
    8   9    Ajax    88
    9  10  jQuery    92
    0   1    java    45
    1   2  python    78