Mathew K Analytics

Lesson 15 · Mastering Pandas

Comprehensive Guide to String Operations and Text Cleaning with Pandas in Python

Let us explore how to clean and manipulate text data in pandas. You will learn to tidy messy strings, extract features, and handle missing or inconsistent…

⬇ Download notebookOpen in Colab ↗

What you'll learn

Data

No separate download needed — the notebook creates or downloads everything it uses.

📓 Full notebook

Download .ipynb

String Operations and Text Cleaning in Pandas#

Let us explore how to clean and manipulate text data in pandas.

You will learn to tidy messy strings, extract features, and handle missing or inconsistent text.

These skills are essential for data analysis or machine learning on real-world data.

We will use the Titanic dataset for hands-on practice.

import warnings; warnings.filterwarnings('ignore')
# Data setup (Titanic Dataset)
import pandas as pd
import numpy as np
np.random.seed(42)
url = 'https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv'
df = pd.read_csv(url)
print(df.shape)
print(df.head(3))
(891, 12)
   PassengerId  Survived  Pclass  \
0            1         0       3   
1            2         1       1   
2            3         1       3   

                                                Name     Sex   Age  SibSp  \
0                            Braund, Mr. Owen Harris    male  22.0      1   
1  Cumings, Mrs. John Bradley (Florence Briggs Th...  female  38.0      1   
2                             Heikkinen, Miss. Laina  female  26.0      0   

   Parch            Ticket     Fare Cabin Embarked  
0      0         A/5 21171   7.2500   NaN        S  
1      0          PC 17599  71.2833   C85        C  
2      0  STON/O2. 3101282   7.9250   NaN        S  

Why clean text data?#

Real-world data is rarely tidy.

Names may be inconsistent. Some fields are empty or filled with symbols or typos.

We must fix these to get meaningful results.

# Inspect text columns
print(df[['Name', 'Sex', 'Cabin']].head())
                                                Name     Sex Cabin
0                            Braund, Mr. Owen Harris    male   NaN
1  Cumings, Mrs. John Bradley (Florence Briggs Th...  female   C85
2                             Heikkinen, Miss. Laina  female   NaN
3       Futrelle, Mrs. Jacques Heath (Lily May Peel)  female  C123
4                           Allen, Mr. William Henry    male   NaN
# Counting missing values in text columns
print(df[['Name', 'Sex', 'Cabin']].isnull().sum())
Name       0
Sex        0
Cabin    687
dtype: int64
# Fill missing Cabin values with 'Unknown'
df['Cabin'] = df['Cabin'].fillna('Unknown')
print(df['Cabin'].unique()[:5])
['Unknown' 'C85' 'C123' 'E46' 'G6']
# Convert names to all lowercase
df['Name_lower'] = df['Name'].str.lower()
print(df['Name_lower'].head())
0                              braund, mr. owen harris
1    cumings, mrs. john bradley (florence briggs th...
2                               heikkinen, miss. laina
3         futrelle, mrs. jacques heath (lily may peel)
4                             allen, mr. william henry
Name: Name_lower, dtype: object
# Remove leading and trailing spaces from 'Cabin'
df['Cabin_clean'] = df['Cabin'].str.strip()
print(df[['Cabin', 'Cabin_clean']].head())
     Cabin Cabin_clean
0  Unknown     Unknown
1      C85         C85
2  Unknown     Unknown
3     C123        C123
4  Unknown     Unknown
# Replace all '/' with '-' in 'Cabin_clean'
df['Cabin_dash'] = df['Cabin_clean'].str.replace('/', '-', regex=False)
print(df[['Cabin_clean', 'Cabin_dash']].head())
  Cabin_clean Cabin_dash
0     Unknown    Unknown
1         C85        C85
2     Unknown    Unknown
3        C123       C123
4     Unknown    Unknown
# Extract the first letter from Cabin codes
df['Cabin_letter'] = df['Cabin_clean'].str[0]
print(df[['Cabin_clean', 'Cabin_letter']].head())
  Cabin_clean Cabin_letter
0     Unknown            U
1         C85            C
2     Unknown            U
3        C123            C
4     Unknown            U
# Does Name contain 'Miss'? Mark as True or False
df['Is_Miss'] = df['Name'].str.contains('Miss')
print(df[['Name', 'Is_Miss']].head())
                                                Name  Is_Miss
0                            Braund, Mr. Owen Harris    False
1  Cumings, Mrs. John Bradley (Florence Briggs Th...    False
2                             Heikkinen, Miss. Laina     True
3       Futrelle, Mrs. Jacques Heath (Lily May Peel)    False
4                           Allen, Mr. William Henry    False
# Count how many unique titles appear in Name
import re
df['Title'] = df['Name'].str.extract(r',\s*([^\.]+)\.')
print(df['Title'].unique())
['Mr' 'Mrs' 'Miss' 'Master' 'Don' 'Rev' 'Dr' 'Mme' 'Ms' 'Major' 'Lady'
 'Sir' 'Mlle' 'Col' 'Capt' 'the Countess' 'Jonkheer']
# Standardize rare titles as 'Other' in Title column
common_titles = ['Mr', 'Mrs', 'Miss', 'Master']
df['Title_clean'] = df['Title'].where(df['Title'].isin(common_titles), 'Other')
print(df['Title_clean'].value_counts())
Title_clean
Mr        517
Miss      182
Mrs       125
Master     40
Other      27
Name: count, dtype: int64
# Replace any digits in names with blank ('')
df['Name_no_num'] = df['Name'].str.replace(r'\d+', '', regex=True)
print(df[['Name', 'Name_no_num']].head())
                                                Name  \
0                            Braund, Mr. Owen Harris   
1  Cumings, Mrs. John Bradley (Florence Briggs Th...   
2                             Heikkinen, Miss. Laina   
3       Futrelle, Mrs. Jacques Heath (Lily May Peel)   
4                           Allen, Mr. William Henry   

                                         Name_no_num  
0                            Braund, Mr. Owen Harris  
1  Cumings, Mrs. John Bradley (Florence Briggs Th...  
2                             Heikkinen, Miss. Laina  
3       Futrelle, Mrs. Jacques Heath (Lily May Peel)  
4                           Allen, Mr. William Henry  
# Combine Last Name and Title as a new feature
df['Last_Title'] = df['Name'].str.split(',').str[0] + '_' + df['Title_clean']
print(df[['Last_Title']].head())
       Last_Title
0       Braund_Mr
1     Cumings_Mrs
2  Heikkinen_Miss
3    Futrelle_Mrs
4        Allen_Mr
# Split 'Name' into 'Last' and 'Rest' columns
df[['Last', 'Rest']] = df['Name'].str.split(',', n=1, expand=True)
print(df[['Last', 'Rest']].head())
        Last                                         Rest
0     Braund                              Mr. Owen Harris
1    Cumings   Mrs. John Bradley (Florence Briggs Thayer)
2  Heikkinen                                  Miss. Laina
3   Futrelle           Mrs. Jacques Heath (Lily May Peel)
4      Allen                            Mr. William Henry
# Make every title uppercase
df['Title_upper'] = df['Title_clean'].str.upper()
print(df[['Title_clean', 'Title_upper']].drop_duplicates().head())
   Title_clean Title_upper
0           Mr          MR
1          Mrs         MRS
2         Miss        MISS
7       Master      MASTER
30       Other       OTHER

Recap: What you learned#

You tried common string cleaning and manipulation tools in pandas:

  • Handling missing values
  • Changing case
  • Trimming whitespace
  • Replacing and cleaning unwanted characters
  • Extracting substrings and using regular expressions
  • Grouping and engineering new features

These skills make your data trustworthy and ready for analysis!

Ready for more?#

Explore the pandas string methods documentation for even more powerful text tricks.

See you in the next video!

Found this useful?

All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.