Reputation: 157
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
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