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

Asked By: ejgza

||

Answers:

using double quotes for the string to compare with worked for me:

df.query('`Bob's Burgers` == "l"')
Answered By: zaki98

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
      
Answered By: wjandrea
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.