我试着像这样查询一个Pandas框架:
inv = pd.read_csv(infile)
inv.columns = ['County', 'Site', 'Role', 'Hostname']
clist = inv.County.unique() # Get list of counties
for county in clist: # for each county
csub = inv.query('County == county') # create a county subset
# ... do stuff on subset
字符串
但我得到一个错误:
pandas.core.computation.ops.UndefinedVariableError: name 'county' is not defined
型
我确信这是一个小错误,但我无法弄清楚。我如何将变量传递给查询方法?
2条答案
按热度按时间cygmwpex1#
根据documentation,您可以使用
@
引用变量:字符串
x4shl7ld2#
格式化字符串函数
我发现了另一个(更通用的)解决方案,可能会很有趣:
format
string function(例如,请参阅6.1.3.2. Format examples
)。字符串
{}
被VariableName
取代。f-Strings
此外,用户pciunkiewicz在评论中提到了另一个使用所谓
f-strings
的解决方案,该解决方案在Python 3.6(2015年8月)中引入:型
一个更一般的
f-strings
例子,取自here:型
PS:我是Python新手。