Skip to content
Related Articles

Related Articles

Remove spaces from column names in Pandas
  • Last Updated : 29 Aug, 2020

Removing spaces from column names in pandas is not very hard we easily remove spaces from column names in pandas using replace() function. We can also replace space with another character. Let’s see the example of both one by one.

Example 1: remove the space from column name

Python




# import pandas
import pandas as pd
  
# create data frame
Data = {'Employee Name': ['Mukul', 'Rohan', 'Mayank',
                          'Shubham', 'Aakash'],
          
        'Location': ['Saharanpur', 'Meerut', 'Agra'
                     'Saharanpur', 'Meerut'],
          
        'Sales Code': ['muk123', 'roh232', 'may989',
                       'shu564', 'aka343']}
  
df = pd.DataFrame(Data)
  
# print original data frame
print(df)
  
# remove special character
df.columns = df.columns.str.replace(' ', '')
  
# print file after removing special character
print("\n\n", df)

Output:



Example 2: replace space with another character

Python




# import pandas
import pandas as pd
  
# create data frame
Data = {'Employee Name': ['Mukul', 'Rohan', 'Mayank',
                          'Shubham', 'Aakash'],
          
        'Location': ['Saharanpur', 'Meerut', 'Agra'
                     'Saharanpur', 'Meerut'],
          
        'Sales Code': ['muk123', 'roh232', 'may989',
                       'shu564', 'aka343']}
  
df = pd.DataFrame(Data)
  
# print original data frame
print(df)
  
# replace space with another character
df.columns = df.columns.str.replace(' ', '_')
  
# print file after removing special character
print("\n\n", df)

Output:

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up
Recommended Articles
Page :