Pandas dataframe query single quotes in a string argument
Question:
How can I escape the single quotes character in the string I want to search for?
Example:
strng = "King's palace"
df.query("fieldname == %s" %(strng))
This query is not returning data because of the quotes. Escaping is not helping.
Answers:
Use this solution:
# Test data
df = pd.DataFrame({'fieldname': ['King's palace', 'Hilton']})
strng = "King's palace"
df.query("fieldname == @strng")
Output:
fieldname
0 King's palace
I tried giving this as df.query(r'fieldname == %s' %(strng))
.
It worked.
Thanks Edchum.
How can I escape the single quotes character in the string I want to search for?
Example:
strng = "King's palace"
df.query("fieldname == %s" %(strng))
This query is not returning data because of the quotes. Escaping is not helping.
Use this solution:
# Test data
df = pd.DataFrame({'fieldname': ['King's palace', 'Hilton']})
strng = "King's palace"
df.query("fieldname == @strng")
Output:
fieldname
0 King's palace
I tried giving this as df.query(r'fieldname == %s' %(strng))
.
It worked.
Thanks Edchum.