Some of the column names in a dataframe have spaces. How can I remove those spaces from column names?

+2 votes

Best answer

You can use either the *replace()* function or the *strip()* function to remove space from column names of a dataframe. Using *replace()*, you can remove all spaces, whereas *strip() *will remove spaces from the beginning and end only.

Here is an example to show how to use these functions:

__Using the replace() function__

>>> import pandas as pd

>>> import numpy as np

>>> a=np.asarray([[1,2,3],[4,5,6],[7,8,9]])

>>> df=pd.DataFrame(a, columns=[' A', 'B ', 'A B'])

>>> df.columns

Index([' A', 'B ', 'A B'], dtype='object')

>>> df.columns = df.columns.str.replace(' ', '')>>> df.columns

Index(['A', 'B', 'AB'], dtype='object')

__Using the strip() function__

>>> df.columns = df.columns.str.strip()>>> df.columns

Index(['A', 'B', 'A B'], dtype='object')