Data Preparation / Data Preprocessing Slides 📂 Introduction · 1 of 13 35 min read

Data Collection in Data Science: The Make-or-Break First Step

Every project lives or dies here. Data collection is gathering raw data from the right sources — databases, APIs, flat files, web scraping, and open datasets — because no model can outrun bad data (garbage in, garbage out). This tutorial covers all five sources with code, structured vs unstructured data (~20/10/70%), quality, bias, and ethics — with animated diagrams.

🗄️

Data Collection in Data Science

The first — and most decisive — step of any project. Gather raw data from databases, APIs, files, the web, and open datasets — because no model can outrun the quality of what you feed it.
Databases APIs Web Scraping Open Datasets

Press Next → or use ← → arrow keys

Section 01

Why It's The Most Critical Step

No recipe rescues rotten ingredients
A world-class chef with spoiled ingredients still serves a bad meal. In data science, the "ingredients" are your data — and data collection is the systematic gathering of raw information from many sources so it can be stored, processed, and analysed.

It's the very first stage of the pipeline, and everything downstream inherits its quality. Perfect cleaning, brilliant features, a state-of-the-art model — none of it can undo data that was biased or badly gathered at the source.
🗑️
Garbage In, Garbage Out

A model trained on poorly collected or biased data produces poor, biased predictions — even if every later step is flawless. Get collection right and the rest of the pipeline has a fighting chance; get it wrong and nothing else can save you.

Section 01 · Diagram

The Data Determines The Destiny

🗑️ Biased / dirty data in ⚙️ Same model 🗑️ Wrong predictions out ✅ Clean, representative in ⚙️ Same model ✅ Trustworthy output out
⚙️
Same Algorithm, Opposite Outcome

The identical model gives trustworthy answers on clean, representative data and biased garbage on dirty data. The lever that decides which you get isn't the algorithm — it's the care you put into collection. That's why this is where a project lives or dies.

Section 02 · Sources

Five Places Data Comes From

Collected Dataset 🗃️ 🛢️ Databases SQL · NoSQL 🔌 APIs JSON · REST 📄 Flat Files CSV · Parquet 🕸️ Web Scraping HTML → data 📦 Open Datasets Kaggle · UCI
🧭
Pick The Source To Fit The Question

Internal databases for company records, APIs for live third-party feeds, flat files for exports and hand-offs, web scraping for data that only exists on pages, and open datasets for benchmarks and public information. Most real projects blend several.

Section 03 · Source 1

Databases — SQL & NoSQL

🗄️
Relational (SQL)
Fixed schemas, tables, joins. PostgreSQL, MySQL, SQLite, SQL Server. Query with SQL — perfect for transactional business data.
📂
Non-Relational (NoSQL)
Flexible schemas for documents, key-values, graphs. MongoDB, Redis, Cassandra, DynamoDB — built to scale horizontally.
🐼
Straight Into pandas
One line lifts query results into a DataFrame, ready for analysis — no manual export/import in between.
import pandas as pd, sqlite3
conn = sqlite3.connect("sales.db")

query = "SELECT customer_id, revenue FROM sales WHERE year = 2024"
df = pd.read_sql(query, conn)   # query result → DataFrame in one step
Section 03 · Source 2

APIs — Data On Request

import requests, pandas as pd

resp = requests.get(url, params={'apikey': KEY})

if resp.status_code == 200:          # 200 OK · 401 auth failed · 429 rate limited
    data = resp.json()               # APIs usually return JSON
    df = pd.json_normalize(data['results'])  # flatten nested JSON → table
🔌
Live, Fresh, But Rate-Limited

APIs (OpenWeatherMap, Alpha Vantage, NASA, REST Countries, and countless others) serve fresh data on demand, usually as JSON. Always check the status code — a 429 means you've hit the rate limit. Respect those limits and add exponential backoff so a burst of requests retries politely instead of getting you blocked.

🗝️
Keep Keys Out Of Your Code

Most useful APIs need an API key. Store it in an environment variable or secrets manager — never hard-code it into a notebook you might share or commit to Git.

Section 03 · Source 3

Flat Files — CSV To Parquet

FormatStrengthsWatch Out
.csvUniversal, human-readableSlow & bulky on large files; no types
.xlsxFamiliar, multi-sheetRow limits; not for big data
.jsonNested / semi-structuredNeeds flattening for tables
.parquetColumnar, typed, compressedNot human-readable
Above ~100 MB, Switch To Parquet

Parquet stores data by column, keeps types, and compresses hard — up to ~80% smaller and 10–100× faster to read than CSV on large datasets. CSV is fine for small, shareable files; past ~100 MB, Parquet saves real time and disk.

Section 03 · Source 4

Web Scraping — When Data Lives On A Page

FetchHTML page ParseBeautifulSoup Extractselect() rows Cleanstrip / typecast StoreDataFrame / DB
⚖️
Scrape Legally And Politely

Tools like BeautifulSoup (static pages) and Playwright / Selenium (JavaScript-rendered pages) turn HTML into data. But always check robots.txt and the site's Terms of Service first, throttle your requests, and never scrape personal data you have no right to. "Technically possible" is not the same as "allowed."

Section 03 · Source 5

Open & Public Datasets

🏆
Kaggle
1M+ datasets, competitions, and free GPU notebooks. The go-to for practice data and learning.
🎓
UCI & Hugging Face
UCI ML Repository for classic benchmarks; Hugging Face for modern NLP, vision, and audio datasets.
🏛️
Government & Search
Google Dataset Search and portals like data.gov surface official, citable public data.
# Kaggle CLI
pip install kaggle
kaggle datasets download -d username/dataset-name
# then, in Python:
df = pd.read_csv("data.csv")
📜
Check The Licence & The Date

"Open" doesn't mean "anything goes" — confirm the licence permits your use (commercial vs research), and check how recent the data is. A benchmark from 2010 may no longer represent today's world.

Section 04 · Data Types

Structured, Semi-Structured & Unstructured

Structured ~20% tables, SQL rows & columns Semi-structured ~10% JSON, XML, HTML, logs Unstructured ~70–80% text, images, audio, video, PDFs — the bulk of the world's data
📊
Most Data Isn't Neat Tables

Only about 20% of enterprise data is neat, tabular structured data; roughly 10% is semi-structured (JSON, XML, logs — flexible but parseable); and a whopping 70–80% is unstructured — text, images, audio, video — usually parked in data lakes like S3 or HDFS. The richest data is also the messiest to collect.

Section 04 · Handling It

Different Data, Different Tools

DataTypical ToolsWhat It Takes
📝 TextspaCy, NLTK, TransformersNLP / tokenization
🖼️ ImagesOpenCV, torchvision, PILComputer vision
🔊 Audiolibrosa, SpeechRecognitionSignal processing
🎬 VideoOpenCV, ffmpegFrame extraction + CV
📄 Documentspdfplumber, PyMuPDFText/table extraction
🧰
Collection Isn't Done At "Download"

For unstructured data, "collecting" it is only half the job — turning a folder of images or a pile of PDFs into model-ready features needs the right toolkit (CV, NLP, or signal processing). Plan for that effort when you choose an unstructured source.

Section 05 · Do It Right

Quality, Bias & Ethics

🔍
Verify The Source
Check reliability and recency, and record how you got it — timestamp, source, API version, query params.
⚖️
Watch For Bias
Ask who's missing from the data. A skewed sample bakes discrimination into every prediction.
🔒
Protect People
Anonymize and encrypt personal data (PII); collect only with consent and a lawful basis (GDPR & friends).
Collect 30–50% More Than You Think You Need

Cleaning and preprocessing typically discard 30–50% of raw data — bad rows, duplicates, missing values. Gathering a healthy surplus up front means you still have enough left to model with once the mess is removed. Collection is an ongoing, deliberate process, not a one-off grab.

Section 06 · Golden Rules

Six Rules For Data Collection

🏅 Data Collection, Distilled
1Remember GIGO. Collection quality caps everything downstream — no model outruns bad data.
2Match source to question — databases, APIs, files, scraping, or open data (often a mix).
3Document the methodology — timestamp, source, version, query — so the data is reproducible.
4Hunt for sampling bias — ask who or what is under-represented before you trust the data.
5Respect law & ethics — robots.txt, ToS, rate limits, consent, and PII protection.
6Over-collect by 30–50% to survive the losses of cleaning, and use Parquet past ~100 MB.
Wrap-Up

You Can Now Gather Data Well

GIGOQuality caps all
5Core sources
20/10/70Struct/semi/unstruct %
Parquet> 100 MB
+30–50%Over-collect
PII 🔒Consent & law
🎯
The Through-Line

Data collection is the first and most decisive step: gather from the right sources (databases, APIs, files, the web, open data), know whether it's structured or not, document it, and guard against bias and privacy risk. Because everything you build later inherits the quality of what you collect here.

📚
Where To Go Next

With raw data in hand, the pipeline moves on to data cleaning (missing values, duplicates, outliers), then transformation and feature engineering — turning the raw material you just collected into something a model can learn from.

🗄️ End of tutorial · Press to review, or click Restart