jinjineos
jinjineos

Reputation: 157

panda query with double quotation python

I want pandas query with text possibly have a double quote. This text variable is passed in as a parameter.

text = 'this is "dave"'

df.query(r'index != "text"')

Here, theres an error

SyntaxError: Python keyword not valid identifier in numexpr query

Therefore, I changed the text to escape double quote

text = text.replace('"','\"')

But the issue persists.

How do I fix this

Upvotes: 2

Views: 649

Answers (1)

jezrael
jezrael

Reputation: 863056

Use @ for pass variable to DataFrame.query:

df = pd.DataFrame({
        'A':list('abc'),
         'B':[4,5,6]

}, index=['this is "dave"','aa','bb'])

print (df)

                A  B
this is "dave"  a  4
aa              b  5
bb              c  6

text = 'this is "dave"'
print (df.query(r'index != @text'))
    A  B
aa  b  5
bb  c  6

Upvotes: 4

Related Questions