1

I'd like to use the .query method to filter a column in a dataframe by a variable but it won't work with a variable, only a string. Anybody know how to make it work with a variable? Thank you.

import pandas as pd    
var="A"

source = {'COL1': ['A','B','C'], 'COL2': ['D','E','F']}
dfsource=pd.DataFrame(source)
print(dfsource)

df2=dfsource.query('COL1=="A"') #Example, this works filtering for value A but not what I need.
df3=dfsource.query('COL1'==var)

print(df2)
print(df3)

1 Answer 1

1

Use @:

import pandas as pd

var = "A"

source = {"COL1": ["A", "B", "C"], "COL2": ["D", "E", "F"]}
dfsource = pd.DataFrame(source)
print(dfsource)

df2 = dfsource.query(
    'COL1=="A"'
)  
df3 = dfsource.query("COL1 == @var") # <-- @

print(df2)
print(df3)

Prints:

  COL1 COL2
0    A    D
1    B    E
2    C    F
  COL1 COL2
0    A    D
  COL1 COL2
0    A    D
Sign up to request clarification or add additional context in comments.

1 Comment

Such a simple but elusive fix! Thank you Andrej!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.