无法在 Pandas 0.14.0 中查询局部变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23974664/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 22:06:29  来源:igfitidea点击:

Unable to query a local variable in pandas 0.14.0

pythonpandas

提问by chrisaycock

I can query an explicit value:

我可以查询一个显式值:

fills.query('Symbol=="BUD US"')

Now I want to query a variable:

现在我想查询一个变量:

In [40]: my_symbol
Out[40]: 'BUD US'

In pandas 0.13.1, I could simply use:

在Pandas 0.13.1 中,我可以简单地使用:

fills.query('Symbol==my_symbol')

This is no longer permitted in pandas 0.14.0 because local variables must be referred to explicitly. So I tried

在 pandas 0.14.0 中不再允许这样做,因为必须显式引用局部变量。所以我试过了

fills.query('Symbol==@my_symbol')

but this returned an error

但这返回了一个错误

KeyError: '__pd_eval_local_my_symbol'

I was able to change some of my other code to use explicit local variables, but this one just will not take. Any thoughts? The dtype is object, if that helps.

我能够更改我的其他一些代码以使用显式局部变量,但这个代码不会。有什么想法吗?dtype 是object,如果有帮助的话。

回答by joris

Seems a bug in 0.14, specifically with strings (works eg with ints). I filed an issue here: https://github.com/pydata/pandas/issues/7300.
As a workaround for now, you can wrap it in a list:

似乎是 0.14 中的一个错误,特别是字符串(例如使用整数)。我在这里提交了一个问题:https: //github.com/pydata/pandas/issues/7300
作为目前的解决方法,您可以将其包装在一个列表中:

In [40]: fills
Out[40]: 
    Price  Symbol
0  109.70  BUD US
1  109.72  BUD US
2  183.30  IBM US
3  183.35  IBM US

In [41]: my_symbol = ['BUD US']

In [42]: fills.query('Symbol==@my_symbol')
Out[42]: 
    Price  Symbol
0  109.70  BUD US
1  109.72  BUD US

回答by choldgraf

The above answer is pretty much right on, but wanted to mention another workaround that I've used in this situation. Basically, just treat the query string like you would any other string where you'd want to insert a variable.

上面的答案非常正确,但想提一下我在这种情况下使用的另一种解决方法。基本上,只需像对待任何其他要插入变量的字符串一样对待查询字符串。

my_symbol = 'BUD US'
fills.query("Symbol=='{0}'".format(my_symbol))

edit: fixed per your comment

编辑:根据您的评论固定