简体   繁体   English

以变​​量为列名的 Pandas 查询

[英]Pandas Query with Variable as Column Name

Passing on new application of information I learned that was part of another question: Unable to query a local variable in pandas 0.14.0传递信息的新应用我了解到这是另一个问题的一部分: 无法在熊猫 0.14.0 中查询局部变量

Credit and thanks to user @choldgraf.感谢用户@choldgraf。 I'm applying his answer from the above link differently.我正在以不同的方式应用上述链接中的答案。

Objective: To use a variable as the column name in a query目标:在查询中使用变量作为列名

Failed examples:失败的例子:

import pandas as pd
fooframe = pd.DataFrame({'Size':['Large', 'Medium', 'Small', 'Tiny'], 'Color':[1, 2, 3, 4]})
myvar = 'Size'
subframe = fooframe.query("myvar == 'Large'")

The code above returns a key error for 'myvar'.上面的代码为“myvar”返回一个关键错误。

import pandas as pd
fooframe = pd.DataFrame({'Size':['Large', 'Medium', 'Small', 'Tiny'], 'Color':[1, 2, 3, 4]})
myvar = 'Size'
subframe = fooframe.query("@myvar == 'Large'")

The code above adds "@" before myvar in the query to reference myvar as a local variable.上面的代码在查询中的 myvar 之前添加了“@”,以将 myvar 作为局部变量引用。 However, the code still returns an error.但是,代码仍然返回错误。

Credit and thanks to user @choldgraf.感谢用户@choldgraf。 I used the technique he mentioned in another post ( Unable to query a local variable in pandas 0.14.0 ) not for the value in the column but for the column name.我使用他在另一篇文章中提到的技术( Unable to query a local variable in pandas 0.14.0 )不是针对列中的值,而是针对列名。

A variable can be used as the column name in a pandas query by inserting it into the query string like so:通过将变量插入到查询字符串中,可以将变量用作 pandas 查询中的列名,如下所示:

import pandas as pd
fooframe = pd.DataFrame({'Size':['Large', 'Medium', 'Small', 'Tiny'], 'Color':[1, 2, 3, 4]})
myvar = 'Size'
subframe = fooframe.query("`{0}` == 'Large'".format(myvar))

(Where backticks are used to bracket the column name, dealing with special characters and spaces in column names.) (其中反引号用于将列名括起来,处理列名中的特殊字符和空格。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM