使用带有pandas eval函数的多个赋值的局部变量 [英] Using local variables with multiple assignments with pandas eval function

查看:72
本文介绍了使用带有pandas eval函数的多个赋值的局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

pandas 帮助文件说(对于 eval):为方便起见,可以使用多行字符串执行多个赋值.

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

但是,我发现这不适用于变量(使用 ipython):

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

这有效:

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

但这不起作用(op、cl、hi、lo 是数据帧 df_price 中的 cols,其中 mult 是浮点数):

But this does NOT work (op, cl, 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)

错误:pandas.computation.ops.UndefinedVariableError: 局部变量 'mult' 未定义

推荐答案

我可以确认局部变量似乎只适用于多行 eval 表达式的第一行.一个可能的解决方法:

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.

更新:

我已经提交了一个拉取请求,并对此问题进行了修复.

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

这篇关于使用带有pandas eval函数的多个赋值的局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆