Pandas DataFrame eval with space in column names

Viewed 7526

I was looking at pandas DataFrame eval method (docs) which I find a nice syntactic sugar and could also help enhancing performances.

This is the example from the docs:

from numpy.random import randn
import pandas as pd

df = pd.DataFrame(randn(10, 2), columns=list('ab'))
df.eval('a + b')

How can I use eval when there is a space in my column names? Example:

df = pd.DataFrame(randn(10, 2), columns=["Col 1", "Col 2"])

I tried this:

df.eval('"Col 1" + "Col 2"')

but this gives error:

TypeError: data type "Col 1" not understood
3 Answers

thank you @Thundzz

    df.columns = df.columns.map(lambda x: x.replace(' ', '_'))

this snippet works well!

Related