63

I'm trying to query a Pandas dataframe like this:

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

But I get an error:

pandas.core.computation.ops.UndefinedVariableError: name 'county' is not defined

I'm sure it's a trivial error, but I can't figure it out. How do I pass a variable to the query method?

3
  • how about 'County == ' + county Commented Jul 31, 2019 at 18:43
  • 1
    inv[inv['County'] == county] Commented Jul 31, 2019 at 18:43
  • 4
    inv.query('County ==@ county') Commented Jul 31, 2019 at 18:44

2 Answers 2

118

According to the documentation, you can reference variables using @:

csub = inv.query('County == @county')
Sign up to request clarification or add additional context in comments.

Comments

15

Format String Function

I found another (more generic) solution that might be interesting: The format string function (for examples, see 6.1.3.2. Format examples).

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

The {} is replaced by VariableName.

f-Strings

In addition, user pciunkiewicz mentioned in a comment another solution using so-called f-strings which were introduced in Python 3.6 (August 2015):

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

A more general f-strings example, taken from here:

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

PS: I am new to Python.

2 Comments

You can clean this up using f-strings which were introduced in Python 3.6: xyz = df.query(f'ColumnName >= {VariableName}').
ATTENTION: Simple string substitution might be unsafe in production, see here github.com/pandas-dev/pandas/issues/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.