1

So I am trying to achieve this I have data frame in pandas and have given a variable where a user inputs a number and if the the number matches the index number in dataframe, i want to display 3 rows above and 3 rows below data from the the dataframe.

what data i have

user_number = int(input('Input Number : '))
print(user_number)

             Country Result
        0      China      N
        1      India      N
        2     Brazil      Y
        3  Indonesia      N
        4     Bhutan      N
        5     Mexico      Y
        6     Canada      N
        7       Peru      N
        8   Honduras      N
        9     Bhutan      N

example if user inputs 5 i want row 2,3,4 and row 6,7,8 to be displayed

What Result i want to achieve:

2     Brazil      Y
3  Indonesia      N
4     Bhutan      N
5     Mexico      Y
6     Canada      N
7       Peru      N
8   Honduras      N
Harold
  • 11
  • 2
  • 1
    `df.iloc[user_input-3:user_input+4]`? If `user_input` is less than `3` throw in `if-else` and handle those edge-cases – Ch3steR Nov 14 '20 at 07:11
  • 4
    `df.iloc[max(user_input-3,0):min(user_input+4, len(df) )]` – Quang Hoang Nov 14 '20 at 07:13
  • 2
    @QuangHoang Cool! but `min(user_input+4, len(df))` is redundant. [`slicing works without raising indexoutofbound exception`](https://stackoverflow.com/q/9490058/12416453) – Ch3steR Nov 14 '20 at 07:24

1 Answers1

0

Use pd.concat with df.iloc:

user_number = int(input('Input Number : '))
print(pd.concat([df.iloc[user_number-3:user_number],df.iloc[user_number:user_number+4]]))

My RAW attempt ;-)

>>> import numpy as np
>>> import pandas as pd
>>> df = pd.DataFrame({'A': np.arange(10)})
>>> user_number = int(input('Input Number : '))
Input Number : 5
>>> pd.concat([df.iloc[user_number-3:user_number],df.iloc[user_number:user_number+4]])
   A
2  2
3  3
4  4
5  5
6  6
7  7
8  8
Wasif
  • 14,755
  • 3
  • 14
  • 34