Pandas eval with backslash in column names

Viewed 313

I have a dataframe like this

df=pd.DataFrame([1,2,3],columns=['a\\b'])

 a\b
0    1
1    2
2    3

and I want to evaluate as expression like 'a\b<2' on this dataframe.

df.eval('a\\b<2')

When I do that I receive the following error message:

a \b <2
           ^
SyntaxError: unexpected character after line continuation character

Does anyone know how can I handle this sittuation? I can't change the column name because this is how the data comes from the datasource (and OPC server).

1 Answers

You cannot use eval when the column name is not a valid python variable name (starts with letter/underscore, letters/numbers/underscore only)

You should do instead:

df = pd.DataFrame([1,2,3],columns=['a\\b'])
df['a\\b'].lt(2)

output:

0     True
1    False
2    False
Name: a\b, dtype: bool
Related