Strip Space in column of pandas dataframe (strip leading, trailing & all spaces of column in pandas)

str.strip  function is used to remove or strip the leading and trailing space of the column in pandas dataframe. Str.replace function is used to strip all the spaces of the column in pandas   Let’s see an Example how to strip leading and trailing space of column and all the spaces of column in a pandas dataframe.

Strip leading, trailing and all spaces of column in pandas:

Stripping the leading and trailing spaces of column in pandas data frames can be achieved by using str.strip function. Let’s see with an example.

First let’s create a data frame

import pandas as pd
import numpy as np

#Create a DataFrame
df1 = {
    'State':[' Arizona AZ ',' Georgia GG ', ' Newyork NY','Indiana IN ','Florida FL '],
   'Score':[62,47,55,74,31]}

df1 = pd.DataFrame(df1,columns=['State','Score'])
print(df1)

df1 will be

strip the space in column of pandas dataframe 1

 

Strip Leading and Trailing Space of the column in pandas:

We will be using str.strip function on the respective column name to strip the leading and trailing space in pandas as shown below.

'''strip leading and trailing space'''

df1['State'] = df1['State'].str.strip()
print (df1)

so all the leading and trailing spaces are removed in the resultant dataframe.

strip the space in column of pandas dataframe 1

 

Strip all the spaces of column in pandas:

We will be using str.replace function on the respective column name to strip all the spaces in pandas dataframe as shown below.


'''Strip all the space'''

df1['State'] = df1['State'].str.replace(" ","")
print (df1)

so all the spaces are removed in the resultant dataframe.

strip the space in column of pandas dataframe 1

Strip Space in column of pandas dataframe (strip leading, trailing & all spaces of column in pandas) p                                                                                                               Strip Space in column of pandas dataframe (strip leading, trailing & all spaces of column in pandas) n