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

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
techvslife
  • 2,273
  • 2
  • 20
  • 26

1 Answers1

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.

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
  • 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) – techvslife Feb 07 '17 at 20:41
  • Your list example just needs a join added: `df.eval("\n".join(..my_list..))` – Stephen Rauch Feb 07 '17 at 20:43
  • 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. – techvslife Feb 07 '17 at 20:45