Skip to content Skip to sidebar Skip to footer

Can I Read A Range Of Rows Using Pandas Data Frame On Some Column Value?

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

Solution 1:

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 enddf[df['names'].isin(subl)] #filter dataset for list of names
2   akash   103
3   sakshi  115
4   vidushi 110

Solution 2:

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

Solution 3:

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  val0    akash  1031   sakshi  1152  vidushi  110

Solution 4:

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

Post a Comment for "Can I Read A Range Of Rows Using Pandas Data Frame On Some Column Value?"