Merve
Merve

Reputation: 43

How to call predefined variable when filtering pandas dataframe with query function

I want to apply some filters and assign new columns to my existing dataframe at the same time.

I have a predefined constant value and since I may want to change at the further steps, I don't want to specify in the code as it is.

I have tried %, $, {} in this code but it didn't work.

my_constant = 0.05
new_df = my_df.query("city == @city_list &  (colA < colB - $my_constant) & (colA > colB + $my_constant)").assign(new_column1 = lambda df: df['colA'] * df['colD'] / df['colB'])

What should I do to get the value from outside of the code?

Upvotes: 0

Views: 176

Answers (2)

Jason Baker
Jason Baker

Reputation: 3706

If I'm understanding your issue correctly, you should use @.

my_constant = 0.05
new_df = (
    my_df
    .query("city in @city_list & (colA < (colB - @my_constant)) & (colA > (colB + @my_constant))")
    .assign(new_column1=lambda df: df['colA'] * df['colD'] / df['colB'])
)

Upvotes: 1

Omnishroom
Omnishroom

Reputation: 263

Using f-strings is the most likely what you are looking for. By starting a quotation with an "f" and then enclosing a variable in "{}" you can insert your variable neatly in strings and other places.

my_constant = 0.5
print(f'{my_constant}')

Here is a link for additional info on the subject

https://datagy.io/python-f-strings/#:~:text=What%20are%20Python%20f-strings%20Python%20f-strings%20%28formatted%20string,embed%20expressions%20inside%20strings%20using%20simple%2C%20straightforward%20syntax.

Upvotes: 0

Related Questions