1.4.6Python & Scientific Computing

Pandas DataFrames and Series basics

3,152 words14 min readdifficulty · medium1 backlinks

Core Concepts from First Principles

What is a Series?

A Series is fundamentally an ordered, labeled, homogeneous array. Let's build the concept:

  1. Start with a simple array: [10, 20, 30, 40]
  2. Add labels (index): Now each value has a name: {'a': 10, 'b': 20, 'c': 30, 'd': 40}
  3. Keep order: Unlike a dict, Series maintains insertion order and supports integer positional access
  4. Add type consistency: All elements share the same dtype (int64, float64, object, etc.)
import pandas as pd
import numpy as np
 
# From list - automatic integer index
s1 = pd.Series([10, 20, 30, 40])
# Index: 0, 1, 2, 3
 
# From list with custom index
s2 = pd.Series([10, 20, 30, 40], index=['a', 'b', 'c', 'd'], name='scores')
# Index: 'a', 'b', 'c', 'd'
 
# From dictionary - keys become index
s3 = pd.Series({'Alice': 85, 'Bob': 92, 'Charlie': 78})

What is a DataFrame?

A DataFrame is a dictionary of Series with aligned indices. Let's derive this:

  1. Start with multiple Series:
    • name_series = Series(['Alice', 'Bob', 'Charlie'])
    • score_series = Series([85, 92, 78])
  2. Align them by a common index: Row 0, Row 1, Row 2
  3. Each Series becomes a column: Column 'name', Column 'score'
  4. Result: A2D table where each column shares the same row index
Figure — Pandas DataFrames and Series basics

Construction Methods: Why Each Exists

Accessing Data: The Three Patterns

Common Operations: Derived from Structure

Filtering (Boolean Indexing)

Adding/Modifying Columns

Common Mistakes and Steel-manning

Active Recall Questions

Recall Explain DataFrames to a 12-Year-Old

Imagine you have a notebook where you track all your friends' video game high scores. Each page has columns: "Friend's Name", "Game", "Score", "Date". That's basically a DataFrame!

A Series is just ONE column from that notebook. Like if you ripped out just the "Score" column - it's a list of numbers, but each number still knows which friend it belongs to (that's the index/label).

A DataFrame is the WHOLE notebook page with ALL the columns together. The cool part? The labels (friend names) stick to each row, so even if you sort by score, you never lose track of whose score is whose. It's like magic sticky notes that never fall off!

Why use Pandas instead of just writing in a notebook? Because you can ask it questions like "Show me everyone who scored over 1000" or "What's the average score?" and it answers in a millisecond. Try doing that with 10,000 friends in a paper notebook!

Connections

  • 1.4.01-NumPy-arrays-and-vectorization - DataFrames are built on NumPy arrays; understanding vectorization helps explain Pandas operations
  • 1.4.02-Python-data-structures - Series is like an enhanced dict; DataFrame combines list and dict concepts
  • 1.4.07-Pandas-data-cleaningand-manipulation - Next step: using these structures for real analysis
  • 1.5.01-Data-visualizationmatplotlib-basics - DataFrames integrate seamlessly with matplotlib for plotting
  • 2.1.03-Feature-engineering-basics - DataFrames are the primary structure for ML feature preparation

#flashcards/ai-ml

What are the two core components of a Pandas Series? :: Values (numpy array) and Index (labels). The index makes each value identifiable even after operations.

Why does a DataFrame require all Series to share the same index?
So operations can automatically align data across columns. When you filter, sort, or merge the index ensures each row's values stay together.
What is the difference between df['col'] and df['col']]?
df['col'] returns a Series (single column). df[['col']] returns a DataFrame (single-column table). Use Series for operations, DataFrame when you need to maintain table structure.
Why must you use & instead of and for DataFrame boolean indexing?
and expects single booleans; df['score'] > 80 returns a Series of booleans. & performs element-wise AND on Series. Same for | vs or.
What does .loc[row_label, col_label] return?
The value at the intersection of the labeled row and column. Uses semantic labels (names/strings), not positions.
What does .iloc[row_int, col_int] return?
The value at the positional intersection (like 2D array indexing). Uses integer positions (0-based), not labels.
When does df.loc[1] differ from df.iloc[1]?
When the DataFrame has a custom (non-integer) index, OR when the integer index is not sequential. .loc[1] finds label 1, .iloc[1] finds position 1.
How do you safely modify a filtered DataFrame?
Use .loc with boolean indexer: df.loc[df['score'] > 80, 'grade'] = 'A'. Chained assignment like df[df['score'] > 80]['grade'] = 'A' may fail (SettingWithCopyWarning).
What is the shape of a DataFrame with 100 rows and 5 columns?
(100, 5) - shape is (n_rows, n_columns). Access via df.shape.
Why use index parameter when creating a Series?
To provide semantic labels instead of default integer index. Makes code self-documenting: sales['Feb'] is clearer than sales[1].

Concept Map

contains

has

enforces

optional

enables O of 1

resolves to

built from

shares

labels via

stores

each column is

Series 1D labeled array

DataFrame 2D labeled table

Values numpy array

Index labels

Dtype homogeneous type

Name optional identifier

Columns column labels

Label to position mapping

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Chalo simple tarike se samajhte hain. Pandas ka core idea yeh hai ki tum apne data ko ek Excel spreadsheet ki tarah handle kar sakte ho, lekin code se — bina copy-paste ke jhanjhat ke. Yahan do main cheezein hain: ek Series jo ek single labeled column hai (jaise ek array jismein har value ka ek naam hota hai), aur ek DataFrame jo actually kai Series ka collection hai jo ek common index (row labels) se aligned hote hain. Matlab, DataFrame ko soch lo ek table jaisa jismein har column ek Series hai aur sabhi columns same row numbers share karte hain.

Ismein sabse zaroori concept hai — labels stick to your data. Yeh line bahut important hai. Jab tum data ko sort karte ho, filter karte ho, ya merge karte ho, tab har value ke saath uska label chipka rehta hai. Isse tumhe wo classic "off-by-one" error nahi aata jo Excel ya plain arrays mein hota hai jab rows aage-peeche ho jaati hain. Aur speed ka bhi kamaal hai — label se value access karna ek O(1)O(1) hash lookup hota hai, aur position se access karna direct array indexing, dono hi super fast. Isliye tum ek million rows ko bhi milliseconds mein filter kar sakte ho.

Yeh kyun matter karta hai? Kyunki real-world AI-ML kaam mein data hi sab kuch hai, aur woh data hamesha tables mein aata hai — CSV files, databases, sensor readings. Agar tumhe data cleaning, filtering, grouping, ya joining aati hai to aadha data science ka kaam ho gaya. Pandas tumhe SQL jaisi power deta hai, par Python ke andar, aur labeled access ke saath jo mistakes ko rokta hai. Isliye Series aur DataFrame ka basic solid hona bahut zaroori hai — yeh tumhare pure ML pipeline ki foundation hai.

Go deeper — visual, from zero

Test yourself — Python & Scientific Computing

Connections