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
Answers:
You should use @variable_name
with @
query=df2.query('cc_vehicle_line==@variable_name')
You can also use ->
- query=df2.query(f’cc_vehicle_line=="{variable_name}"’)
- query=df2.query(f"cc_vehicle_line=='{variable_name}’")
- query=df2.query(‘cc_vehicle_line==@variable_name’)
- query=df2.query("cc_vehicle_line== {0}".format(variable_name))
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
You should use @variable_name
with @
query=df2.query('cc_vehicle_line==@variable_name')
You can also use ->
- query=df2.query(f’cc_vehicle_line=="{variable_name}"’)
- query=df2.query(f"cc_vehicle_line=='{variable_name}’")
- query=df2.query(‘cc_vehicle_line==@variable_name’)
- query=df2.query("cc_vehicle_line== {0}".format(variable_name))