Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - dataframe.loc, boolean on index

I currently have a dataframe:

df = |0 10|
     |1 20|
     |2 30|

I am trying to return a new dataframe, df2 = df['INDEXNAME' < 2], so that it returns only the first two rows.

I've tried:

df.loc[df<100]
df.loc[df['INDEXNAME']<100]

but these are giving me a

KeyError: 'INDEXNAME'

Any thoughts? Thanks!

like image 244
keynesiancross Avatar asked Dec 01 '25 07:12

keynesiancross


1 Answers

You can use query:

df= pd.DataFrame({'value':[10,20,30]}, index = [20,2,0])
df.index.name = "beta"

df.query("beta < 2")
#    value
#beta   
#0     30

or:

df[df.index < 2]
# value
#0   30
like image 114
Psidom Avatar answered Dec 02 '25 19:12

Psidom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!