Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use variable in Pandas query

Tags:

python

pandas

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?

like image 392
Ron Trunk Avatar asked Jul 31 '19 18:07

Ron Trunk


People also ask

How do you use variables in Python query?

In order to do reference of a variable in query, you need to use @ . Instead of filter value we are referring the column which we want to use for subetting or filtering. {0} takes a value of variable myvar1. Incase you want to pass multiple columns as variables in query.

Is query faster than LOC?

The query function seams more efficient than the loc function. DF2: 2K records x 6 columns. The loc function seams much more efficient than the query function.

How do I query a pandas DataFrame?

Pandas DataFrame query() Method The query() method allows you to query the DataFrame. The query() method takes a query expression as a string parameter, which has to evaluate to either True of False. It returns the DataFrame where the result is True according to the query expression.

How do you declare variables in pandas?

If you want to add multiple variables, you can do this with a single call to the assign method. Just type the name of your dataframe, call the method, and then provide the name-value pairs for each new variable, separated by commas. What is this? Honestly, adding multiple variables to a Pandas dataframe is really easy.


1 Answers

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

csub = inv.query('County == @county') 
like image 89
Philip Ciunkiewicz Avatar answered Sep 27 '22 21:09

Philip Ciunkiewicz