nebneb2000
nebneb2000

Reputation: 29

Using a Variable in a .query function

I'm trying to create a function that takes the input name of a value in a column and that value will then be used in a df.query function. However, I cannot figure out how to make it a variable that it recognizes as the input.

This is what I have right now:

def gettingWeeks(stateAbbr, stateName):

    stateCases = cases.query('state == stateName')

But it does not recognize stateName. Is there a way to do this? Thanks!

Upvotes: 1

Views: 450

Answers (1)

I159
I159

Reputation: 31109

Pandas DataFrame.query method expects an expression string created accordingly to its specific syntax. To use variables from the current name space you have to use @ symbol before the name of the variable:

stateCases = cases.query("state == @stateName")

Should work fine.

Here is the doc.

Upvotes: 3

Related Questions