How do I slice X rows from a Dataframe begining at a specific label index in Pandas and Python -


i want specify label index, slice int x rows dataframe. , not know end label. labels timestamps, should not matter. having trouble achieving this, mixing labels , integer numbers of rows wanted.

so if:

df= pd.dataframe(np.random.rand(8,3), columns = list('abc'), index = list('lmnopqrs')) 

how result given code:

df.loc['q':'o':-1] 

but, if know 'q' index? want returns logic this:

df.loc['q':"3 rows only":-1] 

so never know int index 'q' is, know name, , not know in dataframe is. thanks.

i not sure if there better ways this, can use df.index access indexes in dataframe, , df.index.tolist() access index list.

so in case, df.index.tolist() give -

in [13]: df.index.tolist() out[13]: ['l', 'm', 'n', 'o', 'p', 'q', 'r', 's'] 

then, can find index of q in list, using list.index() method , element 2 indexes before q . example -

in [19]: df.index[df.index.tolist().index('q')-2] out[19]: 'o' 

you can use index dataframe , example -

in [20]: df.loc['q':df.index[df.index.tolist().index('q')-2]:-1] out[20]:                   b         c q  0.791467  0.703116  0.268405 p  0.643924  0.434607  0.918549 o  0.630881  0.209446  0.351309 

Comments

Popular posts from this blog

python - ValueError: empty vocabulary; perhaps the documents only contain stop words -

java - UnknownEntityTypeException: Unable to locate persister (Hibernate 5.0) -

ubuntu - collect2: fatal error: ld terminated with signal 9 [Killed] -