Skip to content
Advertisement

Pandas query function not working with spaces in column names

I have a dataframe with spaces in column names. I am trying to use query method to get the results. It is working fine with ‘c’ column but getting error for ‘a b’

import pandas as pd
a = pd.DataFrame(columns=["a b", "c"])
a["a b"] = [1,2,3,4]
a["c"] = [5,6,7,8]
a.query('a b==5')

For this I am getting this error:

a b ==5
  ^
SyntaxError: invalid syntax

I don’t want to fill up space with other characters like ‘_’ etc.

There is one hack using pandasql to put variable name inside brackets example: [a b]

Advertisement

Answer

From pandas 0.25 onward you will be able to escape column names with backticks so you can do

a.query('`a b` == 5') 
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement