简体   繁体   中英

Pandas dataframe slice indexing by index criterias

I often need to do some searching in the index by some higher/lower than criteria in Pandas DataFrame. I have found a way to do it, but it feels a bit cumbersome, or somehow unsmart. This is my current method:

from numpy import linspace
import pandas as pd

df = pd.DataFrame(linspace(1,5,5),index=linspace(0.1,0.5,5))

df

     0
0.1  1
0.2  2
0.3  3
0.4  4
0.5  5

df[(df.index>0.3) * (df.index <0.5)]

     0
0.3  3
0.4  4

It does give me what I wan't, but please suggest a better way if you have one.

I would do it like this. Operating with a float-like index is a bit unusual and can give somewhat unexpected results. In 0.13 (release very shortly), it has much more support, but still operates differently that a 'regular' index. See here

In [4]: df = pd.DataFrame({ 'A' : np.linspace(1,5,5), 'B' : np.linspace(0.1,0.5,5) })

In [5]: df
Out[5]: 
   A    B
0  1  0.1
1  2  0.2
2  3  0.3
3  4  0.4
4  5  0.5

In [6]: df.loc[(df.B>0.3)&(df.B<0.5)]
Out[6]: 
   A    B
2  3  0.3
3  4  0.4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM