- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements