How do you df.query() a column with a name that has an apostrophe
Question:
The column name is: Bob’s Burgers
A workaround could be renaming the column… but I’m curious if you can actually query the above column or if this is indeed a limitation in the parser.
Edit: here’s what I tried
df.query("`Bob's Burgers` == 'dfasdfa'")
I’m getting this error: SyntaxError: Failed to parse backticks
Answers:
using double quotes for the string to compare with worked for me:
df.query('`Bob's Burgers` == "l"')
This seems to be a limitation of the parser when dealing with an odd number of a quote character. For comparison, I can reproduce the same issue with the column called Bob"s
and query `Bob"s` == "dfasdfa"
, but not with the column called 'Bob's
and query `'Bob's` == 'dfasdfa'
. I’m using Pandas 1.4.4.
So, simply switch quote characters, for example:
-
df.query('''`Bob's Burgers` == "dfasdfa"''')
-
df.query("""`Bob's Burgers` == "dfasdfa" """) # Note the trailing space
Or use a variable:
-
v = 'dfasdfa'
df.query("`Bob's Burgers` == @v")
-
col = df["Bob's Burgers"]
df.query("@col == 'dfasdfa'")
-
Note that it’s not possible to use a variable for the column name:
col = "Bob's Burgers"
df.query("@col == 'dfasdfa'")
...
KeyError: False
The column name is: Bob’s Burgers
A workaround could be renaming the column… but I’m curious if you can actually query the above column or if this is indeed a limitation in the parser.
Edit: here’s what I tried
df.query("`Bob's Burgers` == 'dfasdfa'")
I’m getting this error: SyntaxError: Failed to parse backticks
using double quotes for the string to compare with worked for me:
df.query('`Bob's Burgers` == "l"')
This seems to be a limitation of the parser when dealing with an odd number of a quote character. For comparison, I can reproduce the same issue with the column called Bob"s
and query `Bob"s` == "dfasdfa"
, but not with the column called 'Bob's
and query `'Bob's` == 'dfasdfa'
. I’m using Pandas 1.4.4.
So, simply switch quote characters, for example:
-
df.query('''`Bob's Burgers` == "dfasdfa"''')
-
df.query("""`Bob's Burgers` == "dfasdfa" """) # Note the trailing space
Or use a variable:
-
v = 'dfasdfa' df.query("`Bob's Burgers` == @v")
-
col = df["Bob's Burgers"] df.query("@col == 'dfasdfa'")
-
Note that it’s not possible to use a variable for the column name:
col = "Bob's Burgers" df.query("@col == 'dfasdfa'")
... KeyError: False
-