How to use variables inside query in Pandas?

Question:

I have problem quering the data frame in panda when I use variable instead of value.

df2 = pd.read_csv('my.csv')
query=df2.query('cc_vehicle_line==7')

works fine but

df2 = pd.read_csv('my.csv')
query=df2.query('cc_vehicle_line==variable_name')

It throws the message that variable_name is undefined.But it is defined. I cannot use hardcoded value as I need to automate and depending of value of variable_name, select relevant rows.

Am I missing something?

Thanks

Asked By: user437777

||

Answers:

You should use @variable_name with @

query=df2.query('cc_vehicle_line==@variable_name')
Answered By: Zero

You can also use ->

  1. query=df2.query(f’cc_vehicle_line=="{variable_name}"’)
  2. query=df2.query(f"cc_vehicle_line=='{variable_name}’")
  3. query=df2.query(‘cc_vehicle_line==@variable_name’)
  4. query=df2.query("cc_vehicle_line== {0}".format(variable_name))
Answered By: ylnhari
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.