To strip whitespace, whether its leading or trailing, use the strip() method. At first, let us import thr required Pandas library with an alias −
import pandas as pd
Let’s create a DataFrame with 3 columns. The first column is having leading and trailing whitespaces −
dataFrame = pd.DataFrame({ 'Product Category': [' Computer', ' Mobile Phone', 'Electronics ', 'Appliances', ' Furniture', 'Stationery'],'Product Name': ['Keyboard', 'Charger', 'SmartTV', 'Refrigerators', 'Chairs', 'Diaries'],'Quantity': [10, 50, 10, 20, 25, 50]})
Removing whitespace from a single column “Product Category” −
dataFrame['Product Category'].str.strip()
Example
Following is the complete code −
import pandas as pd # create a dataframe with 3 columns dataFrame = pd.DataFrame({ 'Product Category': [' Computer', ' Mobile Phone', 'Electronics ', 'Appliances', ' Furniture', 'Stationery'],'Product Name': ['Keyboard', 'Charger', 'SmartTV', 'Refrigerators', 'Chairs', 'Diaries'],'Quantity': [10, 50, 10, 20, 25, 50]}) # removing whitespace from a single column dataFrame['Product Category'].str.strip() # dataframe print"Dataframe after removing whitespaces...\n",dataFrame
Output
This will produce the following output −
Dataframe after removing whitespaces... Product Category Product Name Quantity 0 Computer Keyboard 10 1 Mobile Phone Charger 50 2 Electronics SmartTV 10 3 Appliances Refrigerators 20 4 Furniture Chairs 25 5 Stationery Diaries 50