Pandas column access w/column names containing spaces

Old post, but may be interesting: an idea (which is destructive, but does the job if you want it quick and dirty) is to rename columns using underscores:

df1.columns = [c.replace(' ', '_') for c in df1.columns]

I think the default way is to use the bracket method instead of the dot notation.

import pandas as pd

df1 = pd.DataFrame({
    'key': ['b', 'b', 'a', 'c', 'a', 'a', 'b'],
    'dat a1': range(7)
})

df1['dat a1']

The other methods, like exposing it as an attribute are more for convenience.


If you like to supply spaced columns name to pandas method like assign you can dictionarize your inputs.

df.assign(**{'space column': (lambda x: x['space column2'])})

While the accepted answer works for column-specification when using dictionaries or []-selection, it does not generalise to other situations where one needs to refer to columns, such as the assign method:

> df.assign("data 2" = lambda x: x.sum(axis=1)
SyntaxError: keyword can't be an expression