在Pandas查询中使用变量

nwlls2ji  于 9个月前  发布在  其他
关注(0)|答案(2)|浏览(110)

我试着像这样查询一个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


我确信这是一个小错误,但我无法弄清楚。我如何将变量传递给查询方法?

cygmwpex

cygmwpex1#

根据documentation,您可以使用@引用变量:

csub = inv.query('County == @county')

字符串

x4shl7ld

x4shl7ld2#

格式化字符串函数

我发现了另一个(更通用的)解决方案,可能会很有趣:format string function(例如,请参阅6.1.3.2. Format examples)。

xyz = df.query('ColumnName >= {}'.format(VariableName))

字符串
{}VariableName取代。

f-Strings

此外,用户pciunkiewicz在评论中提到了另一个使用所谓f-strings的解决方案,该解决方案在Python 3.6(2015年8月)中引入:

xyz = df.query(f'ColumnName >= {VariableName}')


一个更一般的f-strings例子,取自here

>>> name = "Eric"
>>> age = 74
>>> f"Hello, {name}. You are {age}."
'Hello, Eric. You are 74.'


PS:我是Python新手。

相关问题