w3resource

Removing leading and trailing whitespace using str.strip() in Pandas


Pandas: Data Cleaning and Preprocessing Exercise-10 with Solution


Write a Pandas program to remove leading and trailing whitespace using str.strip().

This exercise shows how to clean text data by removing leading and trailing whitespace using str.strip().

Sample Solution :

Code :

import pandas as pd

# Create a sample DataFrame with extra whitespace
df = pd.DataFrame({
    'Name': [' Artair ', ' Pompiliu ', ' Gerry ']
})

# Remove leading and trailing whitespace
df['Name_Cleaned'] = df['Name'].str.strip()

# Output the result
print(df)

Output:

         Name Name_Cleaned
0     Artair        Artair
1   Pompiliu      Pompiliu
2      Gerry         Gerry

Explanation:

  • Created a DataFrame with text data containing leading and trailing whitespace.
  • Used str.strip() to remove the extra spaces around the 'Name' column values.
  • Added a new column 'Name_Cleaned' with the cleaned text.

Python-Pandas Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.