Mridula Gunturi
Mridula Gunturi

Reputation: 187

Using negative numbers in pandas.DataFrame.query() expression

I am trying to use the pandas.DataFrame.query() function as follows:

expression_string = 'ColumnName<(-1000)'
output_dataframe = dataframe.query(expression_string)

The code works with positive numbers, but when negative numbers are passed to the string, as above, it returns the following error:

AttributeError: 'UnaryOp' object has no attribute 'value'

Any suggestions on how to use negative numbers in DataFrame query() expressions? Thank you!!

Upvotes: 8

Views: 2309

Answers (1)

jpp
jpp

Reputation: 164773

I can reproduce this error on pandas v0.20.3 with specific data types; for example, np.float32. The workaround is to cast explicitly as float.

This is a known bug: DataFrame.eval errors with AttributeError: 'UnaryOp'

df = pd.DataFrame({'A': [-3.0, -2.5, -1.5, 3.0]}, dtype=np.float32)

x = 'A>(-1)'

# AttributeError:
res = df.query(x)

# Success:
df['A'] = df['A'].astype(float)
res = df.query(x)

Upvotes: 5

Related Questions