3

The pandas help file says (for eval): As a convenience, multiple assignments can be performed by using a multi-line string.

However, I'm finding that doesn't work with variables (using ipython):

This works:

df_price.eval("op = op * @mult", inplace = True)

But this does NOT work (op, cl, hi, lo are cols in dataframe df_price where mult is a float):

df_price.eval("""op = op * @mult
              cl = cl * @mult
              hi = hi * @mult
              lo = lo * @mult""", inplace = True)

error: pandas.computation.ops.UndefinedVariableError: local variable 'mult' is not defined

4
  • I have submitted a pull request with a fix for this issue. See updated answer. Commented Feb 8, 2017 at 6:07
  • Thank you for submitting the fix. Commented Feb 8, 2017 at 19:04
  • The fix has been merged to main and is tagged as part of milestone 0.20.0. Cheers. Commented Feb 9, 2017 at 22:08
  • That was quick, thanks. Commented Feb 11, 2017 at 18:46

1 Answer 1

2

I can confirm that the local variables appear to only work on the first line of a multi line eval expression. A possible work around:

df_price.eval("""mult = @mult
              op = op * mult
              cl = cl * mult
              hi = hi * mult
              lo = lo * mult""", inplace = True)

This does however have the side effect of creating an extra column.

Update:

I have submitted a Pull Request with a fix for this issue.

Sign up to request clarification or add additional context in comments.

3 Comments

thanks. in that case, I'll do a string replace to replace mult with its value before passing the string to eval. Haven't investigated whether this is any faster than four separate eval statements anyway. The triple quote is clunky--I'd say a semi-colon to separate them is better, or allow a list: df_price.eval(["op = op * @mult", "cl = cl * @mult"], inplace=True)
Your list example just needs a join added: df.eval("\n".join(..my_list..))
Good point, that should work. However, I still think eval should be changed to not need the newline to process multiple commands--list separation is enough.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.