Skip to main content

Lesson 2 of 12

Step 1: Load and Explore the Data

Before training any model, you must understand your data. This step shows you how to create a dataset and explore it.

12 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Create the Dataset

Create the Dataset
# Step 1: Create our email dataset
# In a real project you would load this from a CSV file or database
# Here we create it manually to keep things self-contained

import pandas as pd

# Email dataset: each row is one email
emails = [
    # (email_text, label)
    # 0 = not spam, 1 = spam
    ("Hi Alex, the meeting is rescheduled to Thursday at 3pm. Please confirm.", 0),
    ("WIN A FREE iPhone NOW! Click here to claim your prize immediately!", 1),
    ("Your monthly bank statement is ready. Log in to view it.", 0),
    ("CONGRATULATIONS! You have been selected for a $1000 gift card. Act fast!", 1),
    ("Can you send me the project report by end of day? Thanks, Sarah.", 0),
    ("Urgent! Your account will be suspended. Verify your information now.", 1),
    ("Reminder: Your dentist appointment is tomorrow at 10am.", 0),
    ("Make $5000 a week from home! No experience needed. Limited spots!", 1),
    ("The quarterly financial results are attached for your review.", 0),
    ("FREE pills! Lose 20 pounds in 10 days guaranteed! Order now!", 1),
    ("Team lunch is scheduled for Friday. Please RSVP by Wednesday.", 0),
    ("You won a lottery! Claim your prize of $500,000. Reply with your details.", 1),
    ("Please review the updated terms of service and provide feedback.", 0),
    ("Hot singles in your area! Click here to meet them tonight!", 1),
    ("The server maintenance will occur this Sunday from 2am to 4am.", 0),
    ("Buy cheap medications online! No prescription needed!", 1),
    ("Your package has been shipped. Track it at the link below.", 0),
    ("FINAL NOTICE: Pay now or face legal consequences. Click here.", 1),
    ("Let us catch up this week. Are you free for coffee on Tuesday?", 0),
    ("Earn unlimited income working from home. Sign up free today!", 1),
]

# Convert to pandas DataFrame
df = pd.DataFrame(emails, columns=["email", "label"])

# Explore the data
print("Dataset Overview:")
print(f"  Total emails: {len(df)}")
print(f"  Spam emails (label=1): {df['label'].sum()}")
print(f"  Not spam (label=0): {len(df) - df['label'].sum()}")
print()
print("First 5 rows:")
print(df.head().to_string())
print()
print("Label distribution:")
print(df['label'].value_counts())

Explore the Data

Explore the Data
# Continue from the dataset above

import pandas as pd

emails = [
    ("Hi Alex, the meeting is rescheduled to Thursday at 3pm. Please confirm.", 0),
    ("WIN A FREE iPhone NOW! Click here to claim your prize immediately!", 1),
    ("Your monthly bank statement is ready. Log in to view it.", 0),
    ("CONGRATULATIONS! You have been selected for a $1000 gift card. Act fast!", 1),
    ("Can you send me the project report by end of day? Thanks, Sarah.", 0),
    ("Urgent! Your account will be suspended. Verify your information now.", 1),
    ("Reminder: Your dentist appointment is tomorrow at 10am.", 0),
    ("Make $5000 a week from home! No experience needed. Limited spots!", 1),
    ("The quarterly financial results are attached for your review.", 0),
    ("FREE pills! Lose 20 pounds in 10 days guaranteed! Order now!", 1),
]

df = pd.DataFrame(emails, columns=["email", "label"])

# Explore word patterns
print("Exploring spam patterns:")
print()

spam_emails = df[df["label"] == 1]["email"].tolist()
legit_emails = df[df["label"] == 0]["email"].tolist()

# Count word frequency in each class
from collections import Counter
import re

def get_words(texts):
    all_words = []
    for text in texts:
        words = re.findall(r"\b[a-z]+\b", text.lower())
        all_words.extend(words)
    return Counter(all_words)

spam_words = get_words(spam_emails)
legit_words = get_words(legit_emails)

print("Top 5 words in SPAM emails:")
for word, count in spam_words.most_common(5):
    print(f"  '{word}': {count} times")

print()
print("Top 5 words in LEGITIMATE emails:")
for word, count in legit_words.most_common(5):
    print(f"  '{word}': {count} times")

Tip

Tip

Always explore your data before training a model. Look at the class distribution (is it balanced?), example texts for each class, and common words per class. This exploration tells you what features might be useful and reveals potential issues before you invest time in model training.

Diagram
Loading diagram…

Educational visual guide for step 1 load and explore the data.

Topics in This Module

0/12 done