Lombrosso
Lombrosso

Reputation: 50

Does pandas query takes variables names?

I have a multindex dataframe where the middle index is 'Week'. I would like to filter by this and my code looks like this:

today = date.today()
this_week = today.isocalendar()[1]'
dt_g.query('Week >= 17 and Week <= this_week')

But this returns: UndefinedVariableError: name 'this_week' is not defined

When I put number 19 instead of this_week, query works properly. Also when I print this_week outside the method it returns number 19.

I would like to know why this isn't working properly in this specific example or how can I create query that will filter from week 17 until current week.

Upvotes: 1

Views: 64

Answers (2)

Utsav
Utsav

Reputation: 5918

We can use @ to let the interpreter know that we are passing a variable to query.

dt_g.query('Week >= 17 and Week <= @this_week')

As stated in pandas docs

The query string to evaluate. You can refer to variables in the environment by prefixing them with an ‘@’ character like @a + b.

Upvotes: 1

Kevin Gao
Kevin Gao

Reputation: 95

dt_g.query(f'Week >= 17 and Week <= {this_week}')

This should work.

Upvotes: 0

Related Questions