+1 vote
in Programming Languages by (8.9k points)
Some of the column names in a dataframe have spaces. How can I remove those spaces from column names?

1 Answer

+2 votes
by (71.8k points)
selected by
 
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') 


...