Python Data Science Library Mastery • Training 02
Article-Training • Core Tabular Data Analysis

Pandas

Turn Tables into Decisions: The Everyday Data Analysis Engine

Learn the Pandas workflow that appears in real analytical work: load, inspect, select, clean, transform, aggregate, merge, work with dates, and publish a controlled result.

Business Question → Load → Inspect → Clean → Transform → Group → Join → Publish
ID
Dept
Date
$
101
Fire
Sep
420
↓ Clean → Group → Join
Raw rows → usable decisions
8learning modules
24interactive practices
5rapid review questions
50%certificate threshold
Learning target
Build enough Pandas fluency to clean, combine, summarize and explain common business datasets.
Practice progress0 / 24

Complete 12 of 24 practices (50%) and enter your name to unlock the Certificate of Participation.

MODULE 01
🧠

What Pandas Is — and Why DataFrames Matter

Pandas is Python’s workhorse for labeled, tabular data. Its two core structures — Series and DataFrame — let you organize rows and columns with labels, mix data types, and perform analysis using readable table operations.

👁️
See it this way

Think of a DataFrame as an analytical table with memory: columns have names, rows have an index, and operations usually preserve those labels.

Core ideas

  • Series is one labeled one-dimensional sequence
  • DataFrame is a two-dimensional labeled table
  • Columns can hold different data types
  • Pandas is strongest when table meaning matters as much as the values
Try this
import pandas as pd

data = {
    "Department": ["Police", "Fire", "Parks"],
    "Requests": [420, 315, 188]
}

df = pd.DataFrame(data)
print(df)
print(df["Requests"].mean())
✅

Use Pandas when your problem looks like a spreadsheet, database result, CSV, or reporting table. If the work is mostly dense numerical matrix math, NumPy is usually the lower-level tool.

Practice the decision, not just the syntax

Practice 1
What is Pandas’ primary two-dimensional data structure?
Practice 2
When is Pandas usually the better first choice?
Practice 3
What is a Series?
MODULE 02
🔎

Load Data and Inspect Before You Touch It

A strong Pandas workflow begins with inspection. Before cleaning or calculating, verify columns, shape, data types, missing values, and a small sample of the rows.

👁️
See it this way

Do not start by “fixing” the file. First ask: What arrived? How many rows? Which columns? Which types? What looks suspicious?

Core ideas

  • pd.read_csv() and pd.read_excel() load common business files
  • head(), tail(), sample() reveal records
  • shape and columns describe structure
  • info() and dtypes reveal data types and non-null counts
Try this
import pandas as pd

df = pd.read_csv("service_requests.csv")

print(df.head())
print(df.shape)
print(df.columns)
print(df.dtypes)
df.info()
✅

Inspection is a control step, not a formality. A wrong delimiter, unexpected header, or numeric column loaded as text can invalidate every downstream calculation.

Practice the decision, not just the syntax

Practice 4
Which attribute returns the number of rows and columns?
Practice 5
Which method is most useful for seeing column dtypes and non-null counts together?
Practice 6
Why inspect data before cleaning it?
MODULE 03
🎯

Select, Filter and Sort the Rows You Need

Pandas becomes useful when you can express a business question as a row-and-column selection: which records, which fields, and in what order?

👁️
See it this way

Turn “show me open high-priority requests for District 3” into a Boolean condition plus a short column selection.

Core ideas

  • df['Column'] selects one column
  • loc selects by labels and conditions
  • iloc selects by integer position
  • sort_values() orders the result for review
Try this
high_priority = df.loc[
    (df["District"] == 3) &
    (df["Status"] == "Open") &
    (df["Priority"] == "High"),
    ["RequestID", "Department", "DaysOpen"]
]

high_priority = high_priority.sort_values("DaysOpen", ascending=False)
print(high_priority.head(10))
✅

Use parentheses around each Boolean condition and combine them with & for AND or | for OR. In Pandas, Python’s and/or operators are not the same thing as element-wise table filtering.

Practice the decision, not just the syntax

Practice 7
Which accessor selects rows and columns by label?
Practice 8
What does & mean between Pandas Boolean conditions?
Practice 9
Which method orders rows by one or more columns?
MODULE 04
🧹

Clean Missing Values, Types, Duplicates and Text

Real data is rarely analysis-ready. Pandas gives you a practical cleaning toolkit for missing values, inconsistent text, duplicated rows, and columns stored with the wrong dtype.

👁️
See it this way

Cleaning is not “make everything nonblank.” It is deciding what each field means, what counts as invalid, and how that decision affects the analysis.

Core ideas

  • isna() / notna() detect missing values
  • fillna() replaces missing values when a defensible rule exists
  • drop_duplicates() removes repeated records under chosen keys
  • astype(), to_numeric(), and string methods standardize types and text
Try this
df["Employee"] = df["Employee"].str.strip()
df["Amount"] = pd.to_numeric(df["Amount"], errors="coerce")

df = df.drop_duplicates(subset=["TransactionID"])

df["Department"] = df["Department"].fillna("Unknown")

print(df.isna().sum())
✅

Never fill, drop, or coerce blindly. A missing salary, missing ZIP code, and missing completion date mean different things. Cleaning rules should follow the field’s business meaning.

Practice the decision, not just the syntax

Practice 10
Which method reports missing-value positions?
Practice 11
What does errors="coerce" do in pd.to_numeric()?
Practice 12
Why use subset in drop_duplicates()?
MODULE 05
⚙️

Create and Transform Columns Without Row-by-Row Loops

Analytical tables become valuable when raw fields are turned into business measures, flags, categories, and standardized values. Pandas supports vectorized column operations that are usually clearer than manual row loops.

👁️
See it this way

If the rule can be described as “for this entire column, calculate…”, try a vectorized expression first.

Core ideas

  • Arithmetic can be applied directly to entire columns
  • assign() can create columns in a readable chain
  • map() converts known categories through a lookup mapping
  • where() and mask() support conditional replacement
Try this
rate_map = {"A": 1.00, "B": 0.90, "C": 0.80}

df["NetAmount"] = df["Amount"] - df["Discount"]
df["RateFactor"] = df["Rating"].map(rate_map)
df["Adjusted"] = df["NetAmount"] * df["RateFactor"]
df["NeedsReview"] = df["Adjusted"] > 5000

print(df[["NetAmount", "Adjusted", "NeedsReview"]].head())
✅

Prefer readable vectorized rules. Use apply() when you truly need custom row/column logic, but do not reach for it automatically when a direct Pandas operation already expresses the rule.

Practice the decision, not just the syntax

Practice 13
What is the clearest first choice for Amount minus Discount across every row?
Practice 14
What is map() especially useful for on a Series?
Practice 15
When should apply() be considered?
MODULE 06
📊

Group, Aggregate and Pivot into KPIs

Most reporting questions ask for a summary by something: department, month, category, instructor, branch, product, or customer. groupby() is one of the most important Pandas patterns for turning transaction-level rows into KPIs.

👁️
See it this way

Think “Split → Apply → Combine”: split rows into groups, apply an aggregation, then combine the results into a summary table.

Core ideas

  • groupby() creates groups from one or more keys
  • agg() can calculate several measures at once
  • pivot_table() reshapes summaries into matrix form
  • reset_index() can return grouped keys to regular columns
Try this
kpi = (
    df.groupby("Department", as_index=False)
      .agg(
          Requests=("RequestID", "count"),
          AvgDays=("DaysOpen", "mean"),
          TotalCost=("Cost", "sum")
      )
      .sort_values("Requests", ascending=False)
)

print(kpi)
✅

Choose aggregations that match the KPI definition. count, nunique, sum, mean, median, min, and max answer different business questions — they are not interchangeable.

Practice the decision, not just the syntax

Practice 16
Which method is central to summaries by department or category?
Practice 17
Which aggregation counts distinct values?
Practice 18
What is pivot_table() useful for?
MODULE 07
🔗

Merge Tables Like a Data Professional

Business data rarely lives in one table. Pandas merge() lets you combine datasets through keys using relational ideas similar to SQL joins.

👁️
See it this way

The question is not only “how do I join?” It is “what should one row represent before and after the join, and can the key multiply rows?”

Core ideas

  • merge() combines tables using key columns
  • how='left' preserves all rows from the left table
  • validate= can assert expected one-to-one or many-to-one relationships
  • concat() stacks compatible objects by rows or columns
Try this
employees = pd.read_excel("employees.xlsx")
departments = pd.read_excel("departments.xlsx")

result = employees.merge(
    departments,
    on="DepartmentID",
    how="left",
    validate="many_to_one"
)

print(result.shape)
print(result.head())
✅

Always validate row counts and key uniqueness around a merge. A join can be syntactically correct and still duplicate rows because the key relationship was misunderstood.

Practice the decision, not just the syntax

Practice 19
Which join keeps every row from the left DataFrame?
Practice 20
Why can a merge unexpectedly increase row count?
Practice 21
What can validate="many_to_one" help verify?
MODULE 08
📅

Work with Dates and Build an End-to-End Business Workflow

Dates are where many real reports become analytical. Convert text to datetime, derive month or weekday features, measure durations, then combine filtering, grouping, and exporting into one repeatable workflow.

👁️
See it this way

Instead of manually creating a monthly report, build a pipeline that can rerun next week with a new file and produce the same logic consistently.

Core ideas

  • pd.to_datetime() converts text to datetime values
  • .dt exposes year, month, weekday and other date components
  • Timedelta arithmetic measures elapsed time
  • to_csv() and to_excel() publish results for downstream users
Try this
df["Created"] = pd.to_datetime(df["Created"], errors="coerce")
df["Closed"]  = pd.to_datetime(df["Closed"], errors="coerce")

df["DaysToClose"] = (df["Closed"] - df["Created"]).dt.days
df["Month"] = df["Created"].dt.to_period("M").astype(str)

monthly = (
    df.groupby(["Month", "Department"], as_index=False)
      .agg(Closed=("RequestID", "count"),
           AvgDays=("DaysToClose", "mean"))
)

monthly.to_excel("monthly_service_kpis.xlsx", index=False)
✅

A good production-minded notebook or script separates inputs, validation, transformation, KPI logic, and outputs. That structure makes the analysis easier to audit, rerun, and eventually automate.

Practice the decision, not just the syntax

Practice 22
Which function converts text into Pandas datetime values?
Practice 23
What does df["Created"].dt.month return?
Practice 24
Why export the final KPI table instead of the raw working DataFrame?
5-Question Knowledge Check

Can you explain Pandas without looking at syntax?

Open each item only after answering it in your own words.

1. What is the difference between a Series and a DataFrame?

A Series is one-dimensional and labeled; a DataFrame is a two-dimensional labeled table.

2. Why inspect dtypes before calculating KPIs?

Because numbers or dates loaded as text can break downstream logic.

3. What business question does groupby() answer?

It summarizes measures by one or more grouping keys.

4. Why should you validate a merge?

Repeated keys can silently multiply rows and alter totals.

5. What turns a Pandas notebook into a repeatable workflow?

Clear inputs, validation, transformation logic, KPI definitions, and controlled outputs.

Decision Guide

Pandas, NumPy or SQL?

NeedPandasNumPySQL
Clean and reshape mixed-type labeled tablesExcellentLimitedGood
Dense numerical arrays and matrix operationsGoodExcellentLimited
Filter, group and join very large data at the databaseGood after extractionNot primaryExcellent
Fast exploratory workflow in PythonExcellentGoodGood
Feed cleaned features into Python modelsExcellentExcellentPreparation layer
Official Sources & Further Learning

Grounded in the official Pandas documentation

The technical concepts in this training follow the official Pandas user guide and getting-started tutorials.

Market Skills

What you should be able to say after this training

“I can load and inspect business datasets with Pandas, select and filter records, clean missing values and types, create calculated fields, summarize KPIs with groupby, combine tables safely with merge, work with dates, and export a controlled result.”

Certificate of Participation

Complete at least 12 of the 24 practice cases (50%) and enter your name.

0 / 24 • 0%