Removing leading and trailing whitespace using str.strip() in Pandas
10. Removing Columns with Too Many Missing Values
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.
For more Practice: Solve these Related Problems:
- Write a Pandas program to remove columns that have more than 50% missing values from a DataFrame.
- Write a Pandas program to dynamically determine a threshold and drop columns exceeding that threshold of NaNs.
- Write a Pandas program to drop columns with missing data and report the names of the removed columns.
- Write a Pandas program to remove columns with excessive missing values and then reindex the remaining DataFrame.
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.