python-for-data-engineering

🧠 Python β€” Visual MindMap Mastery (Think in Python, Don’t Memorize It)

The whole philosophy: Don’t ask β€œwhat syntax do I need?” Ask β€œwhat problem am I solving, what’s the input, what’s the output, what are the steps?” Syntax is the last 10%. This doc is built from maps, analogies, memory cards, cheat sheets, decision trees, and active recall β€” not a function list.


πŸ—ΊοΈ THE MASTER PYTHON MIND MAP (home base)

                           PYTHON
                              β”‚
       β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
       ↓                      ↓                      ↓
     THINK                  STORE                   ACT
       β”‚                      β”‚                      β”‚
   Variables              Lists                   Functions
   Conditions             Dictionaries            Modules
   Loops                  Sets                    Classes
   Logic                  Tuples                  APIs
       β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                      ↓
                    DATA ──► Files Β· APIs Β· Databases
                      ↓
                   PROCESS ──► Pandas / NumPy
                      ↓
        ANALYZE ─► AUTOMATE ─► TEST ─► DEPLOY ─► MONITOR

Recall rule: if you can redraw this from memory, you can rebuild most of Python.

πŸ” THE PROBLEM-SOLVING LOOP

PROBLEM ─► UNDERSTAND ─► BREAK INTO SMALL STEPS ─► WRITE LOGIC ─► CODE
       ─► RUN ─► CHECK RESULT ─► DEBUG ─► TEST ─► IMPROVE

Memory: Understand β†’ Break β†’ Code β†’ Test β†’ Improve.

πŸ’» THE COMPUTER MENTAL MODEL

INPUT ─► PROCESS ─► OUTPUT
sales = [100, 200, 300]   # INPUT
total = sum(sales)        # PROCESS
print(total)              # OUTPUT -> 600

The computer is a juicer: fruit in, squeeze, juice out. It never guesses β€” you describe exact steps.



PART A β€” THINK Β· STORE Β· ACT (fundamentals, as memory cards)

Each card draws on this shape β€” WHAT Β· WHY Β· PICTURE Β· TINY CODE Β· MEMORY Β· WATCH OUT β€” condensed to what matters most for that concept.

🟦 VARIABLE

WHAT a name pointing to a value Β· WHY remember/reuse data Β· CODE price = 100
MEM Variable = a label stuck on data Β· WATCH '=' means assign, not "equals"

🟦 DATA TYPES

name="Ravi"; age=30; salary=50000.5; active=True
cities=["Pune","Mumbai"]; cust={"name":"Ravi","age":30}

Convert: int() float() str(). Check: type(x).

🟦 STRING

"Ravi".upper(); f"Ravi is {age} years old."; "  hi ".strip(); "a,b".split(",")

MEM: f-string = drop values into text. WATCH: strip() for dirty data.

🟦 NUMBER

+ - * / //(floor) %(remainder) **(power) Β· WATCH: / gives float; guard divide-by-zero.

🟦 BOOLEAN & COMPARISON

== != > < >= <= β†’ True/False. WATCH: == compares; = assigns.

🟦 IF / ELIF / ELSE

if sales > 100000: cat="High"
elif sales > 50000: cat="Medium"
else: cat="Low"

WATCH: indentation (4 spaces) defines what's "inside".

🟦 LOGICAL OPERATORS

and (both) Β· or (either) Β· not (flip).

🟦 LIST (ordered, changeable)

a=[10,20,30]; a.append(40); a[0]; a[-1]; a[1:3]; a.sort()

🟦 TUPLE (frozen list)

point=(19.99,73.78)   # can't be changed; usable as a dict key

🟦 SET (unique)

list(set(x)) dedupes; x in myset is super fast.

🟦 DICTIONARY (KEY β†’ VALUE β€” the workhorse)

c={"name":"Ravi","age":30}
c["name"]; c.get("phone","NA"); c["phone"]="999"
for k,v in c.items(): ...

It’s JSON, API responses, config, one row of data. WATCH: c["missing"] crashes; c.get() is safe.

🟦 PICK-ONE MAP

ordered + changeable → LIST · fixed → TUPLE · unique → SET · key→value → DICT

🟦 LOOPS

for customer in customers: process(customer)
while not done: step()

WATCH: a while loop must change its condition. break=stop, continue=skip.

🟦 FUNCTION (reusable machine)

def calculate_profit(revenue, cost):
    return revenue - cost

Ask: what input? what output? can I test it alone? can I reuse it?

🟦 PARAMETER vs ARGUMENT vs RETURN

def good(p,q): return p*q     # gives back the number
x = good(100,5) * 2           # works

WATCH (critical): print() SHOWS and returns None; return SENDS a value other code can use.

🟦 SCOPE

GLOBAL visible everywhere Β· LOCAL only inside a function. Prefer passing in / returning out.

🟦 LIST COMPREHENSION

squares=[x*x for x in nums]
big=[o for o in orders if o>10000]

MEM: a loop folded onto one line. Keep it readable.

🟦 CLASS & OBJECT (practical OOP)

class Customer:
    def __init__(self, name): self.name = name   # constructor
    def shout(self): return self.name.upper()
c = Customer("Ravi"); c.shout()                    # 'RAVI'

DECISION: class when state + behavior belong together; plain transform β†’ a function.

🟦 EXCEPTION (controlled failure)

try: amount=float(row["amount"])
except ValueError: amount=None; log.warning("bad amount")

WATCH: never bare 'except: pass' β€” it hides real bugs.

🟦 MODULE & PACKAGE / ENVIRONMENT

from utils import calculate_profit Β· module = .py file, package = folder of modules.

python -m venv .venv; source .venv/bin/activate; pip install -r requirements.txt

MEM: a venv = a clean room per project, so versions never fight.

🟦 GENERATOR (one at a time)

def read_big(path):
    with open(path) as f:
        for line in f: yield line     # hand one out, pause, resume

Perfect for files too big for RAM.



PART B β€” DATA Β· PROCESS Β· AUTOMATE (the engineer’s toolkit)

πŸ“ FILES

with open("sales.txt") as f: data=f.read()   # 'with' auto-closes safely

🧾 CSV / JSON / EXCEL

import csv, json
# csv.DictReader(f) -> each row a dict; json.loads/dumps; pandas.read_excel (needs openpyxl)

JSON object {} ⇄ Python dict; JSON array [] ⇄ Python list.

🐼 PANDAS β€” the data engine

import pandas as pd
df = pd.read_csv("sales.csv")
df[(df["units"]>0) & (df["region"]=="West")]      # filter (use &, not 'and')
df["revenue"] = df["units"] * df["unit_price"]     # new column (vectorized)
df.groupby("region")["revenue"].sum()              # aggregate
pd.merge(sales, customers, on="customer_id", how="left")   # join
df["units"].fillna(0); df.drop_duplicates("order_id")

WATCH: pandas works in memory on ONE machine β€” huge data needs a DB/Spark.

PANDAS ⇄ SQL

SELECT cols β†’ df[["a","b"]]   WHERE β†’ df[df.x>5]   GROUP BY β†’ df.groupby("x")
JOIN β†’ pd.merge(a,b,on=,how=) ORDER BY β†’ df.sort_values("x")   DISTINCT β†’ df.drop_duplicates()

πŸ”’ NUMPY

np.array([1,2,3]) * 2 β†’ vectorized fast math. pandas is built on NumPy.

🌐 APIs

import requests
r = requests.get(url, params={...}, headers={"Authorization":f"Bearer {key}"}, timeout=10)
r.raise_for_status(); data = r.json()

GET=read POST=create PUT/PATCH=update DELETE=remove Β· 200 okΒ·400 badΒ·401 unauthΒ·404 missingΒ·429 rateΒ·500 server WATCH: always set a timeout; handle failures; retry with backoff; respect rate limits.

πŸ—„οΈ DATABASES + PYTHON

import sqlite3, pandas as pd
with sqlite3.connect("sales.db") as conn:
    df.to_sql("sales", conn, if_exists="replace", index=False)
    top = pd.read_sql_query("SELECT customer_id, SUM(revenue) r FROM sales GROUP BY customer_id ORDER BY r DESC LIMIT ?", conn, params=(3,))

WATCH (security): use parameters (?), never f-string values into SQL β€” SQL injection.

πŸ€– AUTOMATION

from pathlib import Path; import shutil
for csv in Path("data").glob("*.csv"):
    ...
    shutil.move(str(csv), f"archive/{csv.name}")

πŸ“£ LOGGING

DEBUG < INFO < WARNING < ERROR < CRITICAL
import logging; logging.basicConfig(level=logging.INFO)
log=logging.getLogger("job"); log.info("started"); log.error("file missing")

MEM: print is for learning; logging is for production.

πŸ” CONFIG & SECURITY

import os; password=os.getenv("DB_PASSWORD")   # never hardcode/commit secrets

βœ… TESTING

def test_profit(): assert calculate_profit(200,120)==80

Test edges (zero, negative, empty, bad type). Run with pytest -q.



PART C β€” CAPSTONE: SALES AUTOMATION & ANALYTICS

β€œEvery morning, automatically collect sales data, clean it, identify bad records, calculate KPIs, store the results in a database, and generate a management report.”

BUSINESS REQUEST
  ─► EXTRACT (csv/excel/api/db)
  ─► VALIDATE + CLEAN (nulls, dupes, bad dates, negative sales, bad types)
  ─► TRANSFORM (revenue, cost, profit, margin, AOV, by customer/region/product/month)
  ─► BUSINESS RULES (profit<0β†’LOSS Β· margin>30%β†’HIGH_MARGIN Β· sales>targetβ†’MET)
  ─► LOAD (SQLite) ─► QUERY BACK ─► REPORT ─► EMAIL ─► LOG every step ─► handle every failure

Production-readiness checklist: error handling Β· logging Β· config Β· secrets via env Β· tests Β· docs/README Β· reusable functions Β· clean structure Β· requirements.txt Β· performance aware Β· parameterized SQL Β· monitoring/log trail.



PART D β€” SCALE, STRUCTURE & SHIP

⚑ PERFORMANCE

Is it actually slow? ─► MEASURE ─► find bottleneck ─► optimize ─► MEASURE again

set lookup β‰ˆ instant vs scanning a list Β· avoid needless loops Β· vectorize in pandas Β· generators for big streams Β· push work to the database Β· profile before guessing.

🧡 CONCURRENCY (concept)

I/O-bound (many API/file waits) β†’ threads/async. CPU-bound (heavy math) β†’ multiprocessing.

πŸ—οΈ PROJECT STRUCTURE

sales_automation/
β”œ src/   main.py extract.py transform.py load.py utils.py
β”œ tests/ Β· config/ Β· data/ Β· logs/
β”œ requirements.txt  README.md  .gitignore

🌿 GIT / πŸš€ DEPLOYMENT / 🐳 DOCKER

add/commit β†’ branch β†’ PR β†’ review β†’ merge (never commit secrets). Deploy shapes: scheduled job (cron/Airflow/Databricks Job), server, container, cloud function. Docker = code+deps+env β†’ one container that runs the same everywhere.

πŸ”— WHERE PYTHON SITS

SOURCES ─► PYTHON ─► SQL ─► DATA PLATFORM ─► BI (Power BI)
Python = glue/logic/automation/APIs Β· SQL = set-based Β· Pandas = local/moderate Β· PySpark/Databricks = big distributed


PART E β€” RECALL ENGINE

🧭 DECISION TREE

store many ordered/changeable → LIST · unique → SET · fixed → TUPLE · key→value → DICT
repeat β†’ FOR/WHILE Β· decide β†’ IF Β· reuse logic β†’ FUNCTION Β· tables β†’ PANDAS
talk to a system β†’ API Β· read a file β†’ FILE/PANDAS Β· records β†’ DATABASE+SQL
might fail β†’ TRY/EXCEPT Β· run on a schedule β†’ SCRIPT+SCHEDULER Β· huge data β†’ DB/SPARK

🧩 BUSINESS-PROBLEM FRAMEWORK

BUSINESS QUESTION ─► INPUT? ─► OUTPUT? ─► STEPS? ─► DATA STRUCTURES? ─► FUNCTIONS?
 ─► EXTERNAL SYSTEMS? ─► WHAT CAN FAIL? ─► HOW TO TEST? ─► HOW TO DEPLOY?

❓ THE 10 QUESTIONS BEFORE WRITING CODE

1 What problem? 2 Input? 3 Output? 4 Split into functions? 5 Which data structure? 6 What can go wrong? 7 How to test? 8 Once or repeatedly? 9 Maintained by someone? 10 How runs in production?

🐞 DEBUGGING MIND MAP

BUG β†’ ERROR (read message) / WRONG RESULT (check logic) β†’ ISOLATE β†’ FIX β†’ TEST β†’ PREVENT

Read a traceback bottom-up: last line = what broke; lines above = where.

πŸ“„ ONE-PAGE CHEAT SHEET

VARIABLE store Β· IF decide Β· FOR each Β· WHILE repeat Β· LIST ordered Β· TUPLE fixed
SET unique · DICT key→value · FUNCTION reusable · RETURN give back · CLASS blueprint
TRY/EXCEPT handle errors Β· MODULE reusable file Β· PANDAS tables Β· API program↔program
JSON structured Β· LOGGING app diary Β· TEST verify Β· ENV clean room Β· GENERATOR one-at-a-time
=assign · ==compare · is→only for None · &,| in pandas (not and/or)

🧠 MASTER RECALL MAP

PYTHON ─► PROBLEM ─► INPUT ─► DATA STRUCTURES ─► CONDITIONS ─► LOOPS ─► FUNCTIONS
 ─► FILES/APIs/DATABASES ─► PANDAS ─► ANALYSIS ─► AUTOMATION ─► ERROR HANDLING
 ─► TESTING ─► LOGGING ─► PROJECT STRUCTURE ─► DEPLOYMENT ─► PRODUCTION

🏁 PROJECT-READY TEST

You’re ready not when you can define β€œlist,” but when handed an unfamiliar requirement you independently: understand it β†’ define input/output β†’ break into steps β†’ choose data structures β†’ write functions β†’ read data β†’ transform β†’ connect API/DB β†’ handle errors β†’ log β†’ test β†’ debug β†’ optimize β†’ package β†’ deploy β†’ monitor. That reflex β€” think in Python β€” is the whole point. πŸš€