safex
safex

Reputation: 2514

Pandas query() with math functions

Consider the following dataframe where I would like to use query to keep only rows where floor(A/100) is above a certain threshold:

import pandas as pd    
df = pd.DataFrame({
         'A':[177,887,945,412,231,314],
         'B':[5,3,6,9,2,4],
})

I tried:

import math
df.query('math.floor(A/100) > 2')

Python throws UndefinedVariableError: name 'math' is not defined. I guess the way query() handles the string is not able to parse math as a module prefix. Any ideas?

A pipeable solution is strictly preferred.

Upvotes: 0

Views: 1037

Answers (1)

Mayank Porwal
Mayank Porwal

Reputation: 34086

Import math module and remove math from query command.

import math

In [1909]: df.query('floor(A/100) > 2')
Out[1909]: 
     A  B
1  887  3
2  945  6
3  412  9
5  314  4

Upvotes: 2

Related Questions