python - Using lists in a pandas query
问题描述
I am performing a query on a DataFrame:
Index Category
1 Foo
2 Bar
3 Cho
4 Foo
I would like to return the rows where the category is "Foo" or "Bar". When I use the code:
df.query("Catergory==['Foo','Bar']")
This works fine and returns:
Index Category
1 Foo
2 Bar
4 Foo
However in future I will want the filter to be changed dynamically so I wrote:
filter_list=['Foo','Bar']
df.query("Catergory==filter_list")
Which threw out the error:
UndefinedVariableError: name 'filter_list' is not defined
Other variations I tried with no success were:
df.query("Catergory"==filter_list)
df.query("Catergory=="filter_list)
Respectively producing:
ValueError: expr must be a string to be evaluated, <class 'bool'> given
SyntaxError: invalid syntax
解决方案
Use @
to reference variables in query
:
filter_list=['Foo','Bar']
df.query("Category == @filter_list")
Output:
Index Category
0 1 Foo
1 2 Bar
3 4 Foo
推荐阅读
- c# - 批处理文件启动应用程序并传递多个参数将空格切换为á
- c# - 如何在控制器操作中访问 JwtBearer 身份验证处理程序配置?
- excel - Excel powerquery:如何创建一个包含其他列值总和的列?
- json - 我想更新 json 数据类型列中的整个 json
- ruby - 如何使用 Curb 浏览 URL 数组
- swift - 多部分/表单数据的问题,图片上传正常,但其他表单数据没有发送到服务器
- coldfusion - Canonicalize() 函数将字符转换为空白
- security - 使用 JWT 进行身份验证时是否可以消除私钥攻击向量?
- django - 在 django 中使用过滤创建聚合查询
- python - 如何从数据框每一行中的一系列数字中选择特定值