Python – Strip whitespace from a Pandas DataFrame



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
Updated on: 2021-09-15T12:28:27+05:30

919 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements