5.4.21Scientific Computing (Python)

Pandas — Series, DataFrame, indexing, groupby, merge, pivot

2,102 words10 min readdifficulty · medium

WHY does pandas exist?

NumPy gives you fast arrays, but arrays are addressed by integer position only. Real data has names: a row is "customer 1023", a column is "revenue". Pandas adds a label axis (the index) so that:

  1. Alignment is automatic — adding two Series matches by label, not position.
  2. Missing data has a homeNaN fills where labels don't match.
  3. Heterogeneous columns coexist — int, float, string, datetime in one table.
import pandas as pd
s = pd.Series([10, 20, 30], index=["a", "b", "c"])
df = pd.DataFrame({"x": [1, 2], "y": [3, 4]}, index=["r0", "r1"])

HOW alignment really works (derive it from scratch)

Think of a Series as a partial function f:IndexValuef : \text{Index} \to \text{Value}. When you do s1 + s2, pandas does NOT add element 0 to element 0. It computes:

(s1+s2)[k]={s1[k]+s2[k]kidx(s1)idx(s2)NaNotherwise(s_1 + s_2)[k] = \begin{cases} s_1[k] + s_2[k] & k \in \text{idx}(s_1)\cap \text{idx}(s_2)\\[4pt] \text{NaN} & \text{otherwise}\end{cases}


Indexing: the three doors ([], .loc, .iloc)


GroupBy: Split → Apply → Combine

result[g]=f({rows r:key(r)=g})\text{result}[g] = f\big(\{ \text{rows } r : \text{key}(r) = g \}\big)

Figure — Pandas — Series, DataFrame, indexing, groupby, merge, pivot

Merge: SQL-style joins by key


Pivot: long → wide reshaping


Common mistakes (Steel-man + fix)


Active recall

Recall Cover and answer
  • Q: What two arrays make a Series? → values + index.
  • Q: Why is a + b with mismatched indices full of NaN? → alignment takes the union, unmatched labels → NaN.
  • Q: .loc vs .iloc on slice endpoints? → loc inclusive (label), iloc exclusive (position).
  • Q: Three steps of groupby? → split, apply, combine.
  • Q: Default how in merge? → inner.
  • Q: When must you use pivot_table instead of pivot? → when (index,column) pairs repeat (need aggregation).
Recall Feynman: explain to a 12-year-old

Imagine a big chart of lockers, each with a name tag (the index). A Series is one column of lockers; a DataFrame is the whole wall. When you add two columns of lockers, you match them by name tag, not by which is first — if a name is missing on one side, that locker stays empty (NaN). Groupby is sorting kids into teams by their team-shirt colour and counting each team. Merge is gluing two charts together using a shared ID column, like matching school IDs to test scores. Pivot is rotating a long list into a neat grid.


Flashcards

What is a pandas Series structurally?
A 1-D labelled array = aligned (values array, index array).
Why does adding two Series with different indices produce NaN?
Pandas aligns by the union of labels; unmatched labels have no partner, so the result is NaN.
Difference between .loc and .iloc on a slice?
.loc is label-based and inclusive of the stop; .iloc is position-based and excludes the stop.
What are the three phases of groupby?
Split rows by key, apply a function per group, combine results into one labelled object.
What is the default join type in pd.merge?
inner (keeps only keys present in both tables).
When must you use pivot_table instead of pivot?
When the (index, column) combination is not unique — pivot_table aggregates duplicates, pivot raises an error.
How do you safely set values on filtered rows?
Use a single .loc call: df.loc[mask, "col"] = value (avoid chained indexing).
What does how="outer" return in a merge?
The union of keys from both tables, filling NaN where one side lacks a match.
Is df.groupby("k") eager or lazy?
Lazy — it returns a GroupBy object; computation happens only when an aggregation/apply is called.

Connections

  • NumPy — each pandas column is a NumPy array; vectorized ops underneath.
  • SQL Joins — merge mirrors INNER/LEFT/RIGHT/OUTER JOIN semantics.
  • Split-Apply-Combine — the general data-analysis pattern groupby implements.
  • Tidy Data — pivot/melt convert between long (tidy) and wide layouts.
  • Hash Tables — the index uses hashing for O(1)O(1) label lookup.
  • Missing Data / NaN — alignment is the main source of NaNs.

Concept Map

glue label onto

indexes

columns share row index

enables

union then reindex

no match yields

accessed via

by label inclusive

by position exclusive

split rows by key

apply then combine

NumPy array
integer position

Index
label axis

Series
1-D labelled

DataFrame
2-D labelled table

Alignment by label

NaN for missing labels

Selectors

.loc label-based

.iloc position-based

GroupBy
split-apply-combine

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Dekho, pandas ka core idea bahut simple hai: ek Series matlab ek column jisme har value ke saath ek label (index) chipka hua hota hai, aur ek DataFrame matlab aise columns ki ek poori table jo ek hi row-index share karte hain. Sabse important baat — pandas data ko label se align karta hai, position se nahi. Isiliye jab tum do Series jodte ho aur unke index match nahi karte, to wahan NaN aa jaata hai. Yeh feature hi pandas ko itna powerful banata hai.

Indexing ke liye do darwaze yaad rakho: .loc label se kaam karta hai aur slice mein stop bhi include hota hai; .iloc position se kaam karta hai aur Python ki tarah stop exclude hota hai. Beginners yahin galti karte hain. Aur agar filtered rows mein value set karni hai to hamesha single .loc[mask, "col"] = val use karo, warna SettingWithCopyWarning aayega aur change lost ho jayega.

Groupby ka funda hai split-apply-combine: rows ko key ke hisaab se teams mein baant do, har team par function (mean, sum) chalao, phir result ko ek table mein jod do. Merge SQL join jaisa hai — on="key" se do tables ko jodta hai, aur how decide karta hai kaun se keys bachenge (default inner = sirf common keys). Pivot long data ko wide grid mein ghuma deta hai; agar (row, column) pair repeat ho to pivot_table use karo jo automatically aggregate kar deta hai.

Exam aur real projects dono mein yeh 5 cheezein 80% kaam karwa deti hain. Inhe ratna nahi, samajhna hai — bas yaad rakho ki sab kuch labels ke alignment par based hai, baaki sab us idea ka extension hai.

Go deeper — visual, from zero

Test yourself — Scientific Computing (Python)

Connections