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

Time:09-30

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?

CodePudding user response:

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 are Python f-strings Python f-strings (formatted string,embed expressions inside strings using simple, straightforward syntax.

CodePudding user response:

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'])
)
  • Related