Home »
Python »
Python Programs
Python - Pandas Strip Whitespace
Given a Pandas DataFrame, we need to strip whitespaces from the values of particular columns.
By Pranit Sharma Last updated : September 27, 2023
Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.
The string is a group of characters, these characters may consist of all the lower case, upper case, and special characters present on the keyboard of a computer system. A string is a data type and the number of characters in a string is known as the length of the string.
Problem statement
Given a Pandas DataFrame, we need to strip whitespaces from the values of particular columns.
Pandas Strip Whitespace
Suppose we have a DataFrame of some employee, and we have a column Name, now we have some extra whitespace in the name of the employee, we will strip this white space with the help of str.strip() method.
Let us understand with the help of an example,
Python program to strip whitespaces from the values of particular columns
# Importing pandas package
import pandas as pd
# Creating a dictionary
d = {
'Employee':['Pranit Sharma ', 'Rahul Goyal ', 'Keshav Mangal ', 'Sudhir Sharma '],
'Location':['Gwalior','Agra','Jaipur','Delhi'],
'Department':['Sales','Development','Analyst','HR']
}
# Creating a DataFrame
df = pd.DataFrame(d)
# Display created DataFrame
print("Original DataFrame:\n",df,"\n")
# Removing Whitespaces
df['Employee'] = df['Employee'].str.strip()
# Display modified DataFrame
print("Modified DataFrame:\n",df)
Output
The output of the above program is:
Python Pandas Programs »