Can I read a range of rows using pandas data frame on some column value?

Viewed 4543

This is my data,

prakash  101
Ram      107
akash    103
sakshi   115
vidushi  110
aman     106
lakshay  99

I want to select all rows from akash to vidushi or all rows from Ram to aman. In real scenarios, there will be thousand of rows and multiple columns and I will be getting multiple queries to select a range of rows on the basis of some column value. how can i do that?

4 Answers

Heres the right way to do it..

start = 'akash'
end = 'vidushi'

l = list(df['names']) #ordered list of names
subl = l[l.index(start):l.index(end)+1] #list of names between the start and end

df[df['names'].isin(subl)] #filter dataset for list of names
2   akash   103
3   sakshi  115
4   vidushi 110

Create some variables (which you can adjust), then use .loc and .index[0] (note: df[0] can be replaced with the name of your header, so if your header is called Names, then change all instances of df[0] to df['Names']:

var1 = 'Ram'
var2 = 'aman'
a = df.loc[df[0]==var1].index[0]
b = df.loc[df[0]==var2].index[0]
c = df.iloc[a:b+1,:]
c

output:

    0       1
1   Ram     107
2   akash   103
3   sakshi  115
4   vidushi 110
5   aman    106

try set_index then use loc

df = pd.DataFrame({"name":["prakash","Ram","akash","sakshi","vidushi","aman","lakshay"],"val":[101,107,103,115,110,106,99]})
(df.set_index(['name']).loc["akash":"vidushi"]).reset_index()

output:

      name  val
0    akash  103
1   sakshi  115
2  vidushi  110

You can use the range to select rows

print x[2:4]

#output
akash    103
sakshi   115
vidushi  110
aman     106

If you want to fill the values based on a specific column you can use np.where

Related