To remove spaces from column names in Pandas DataFrame, the most efficient way is to use the “.columns” attribute with the “str.replace()” method. It directly operates on the index of the columns (which is a string index) and performs string replacement.
import pandas as pd # Sample DataFrame data = {'Col 1': [1, 2, 3], 'Col 2': [ 4, 5, 6], 'Col 3': [7, 8, 9]} df = pd.DataFrame(data) print(df) # Remove all spaces df.columns = df.columns.str.replace(' ', '') print(df)
Output
You can see from the above figure that we removed space between column names.
Replacing spaces with underscores
We can also replace spaces with underscores if we have that kind of requirement. In that case, we must replace ” “ with “_”.
import pandas as pd data = {'Col 1': [1, 2, 3], 'Col 2': [ 4, 5, 6], 'Col 3': [7, 8, 9]} df = pd.DataFrame(data) print(df) # Replace space with underscore (_) df.columns = df.columns.str.replace(' ', '_') print(df)
Output
Remove leading/trailing spaces from column names
You can also remove leading/trailing spaces from column names using the “.strip()” method.
import pandas as pd data = {' Col 1 ': [1, 2, 3], ' Col 2 ': [ 4, 5, 6], ' Col 3 ': [7, 8, 9]} df = pd.DataFrame(data) print(df) # Remove leading and trailing whitespaces df.columns = df.columns.str.strip() print(df)
Output