1

I have a dataframe like this. I want to pick the rows above if a certain condition is met. For example here if number > 2, then i want to pick the rows with John, richard and paul. i.e the rows with numbers that led up to three. I also want to pick the 5 rows above myers. i.e myers, Jessica, Ashton, Whiley, Jason.

   name     number
   Adrian     1
   Peter      2
   John       1  
   Richard    2
   Paul       3 
   Ashley     1
   Winchester 0
   Jason      1
   Whiley     2 
   Ashton     3
   Jessica    4
   myers      5

The output could look like this

 name    number
 John       1
 Richard    2
 Paul       3
 Jason      1
 Whiley     2 
 Ashton     3
 Jessica    4
 myers      5
CodeGeek123
  • 4,341
  • 8
  • 50
  • 79

2 Answers2

6

This awkwardly works:

def get_number(n):
    position = df[df['number']==n].index[0]
    find = range(position - (n-1), position + 1)
    return df.loc[find]

print get_number(3)
zipa
  • 27,316
  • 6
  • 40
  • 58
  • Thanks Zipa. One question though for data sets that done contain the condition I get an index error on line 2 : IndexError: index 0 is out of bounds for axis 0 with size 0 – CodeGeek123 Apr 28 '17 at 15:36
0
def Select_no(n):
    position = df[df['number']==n].index[0]
    find = range(position - (n-1), position + 1)
    return df.loc[find]

df1 = Select_no(3)
df2 = df[7:]
df1 = df1.append(df2)

you could also do df1.reset_index(inplace=True), if you want your index to be starting from 0. enter image description here

Shubham R
  • 7,382
  • 18
  • 53
  • 119