1
CMSC 320
INTRODUCTION TO DATA SCIENCE
Pandas
“A Python Library for Manipulating Tabular Data”
Lecture 03
FARDINA FATHMIUL ALAM
fardina@umd.edu
student | quiz | hours |
A | 88 | 4.5 |
B | 73 | 2.0 |
C | 91 | 5.0 |
answers
Which students improved?
Where are missing values?
What patterns matter?
pandas
2
Topics to Cover
These skills are essential for effective data analysis, collaboration, and handling data in real-world projects.
Python: User-friendly language for data analysis.
Git: Helps manage code and data changes in teams.
Pandas: Simplifies data cleaning and manipulation.
Databases: Needed for storing/retrieving data efficiently.
Chapter 4: Pandas
What is Pandas?
A fundamental data science tool for Python.
An open-source library providing high-performance, easy-to-use data structures and data analysis tools. Built on top of NumPy, it is essential for structured (tabular) data.
Key Data Structures
view_stream
Series
1D labeled array
table_chart
DataFrame
2D tabular structure
Why Pandas?
check_circle Easy Missing Data Handling: Built-in mechanisms for cleaning and handling incomplete datasets.
check_circle Powerful Aggregations: Flexible split-apply-combine operations for easy data grouping.
check_circle Quick Operations: High-performance filtering, sorting, merging, and reshaping.
check_circle Robust I/O Support: Read/write seamlessly across CSV, Excel, SQL, and JSON formats.
The Origin of "Pandas" (Derived from "Python Data Analysis Library")
Started in 2008 by Wes McKinney to deliver a high-performance, flexible tool capable of executing advanced quantitative analysis on financial datasets.
4
Where pandas fits in data science
Most real projects are not “train a model first.” They begin with understanding a table.
1. Load
2. Inspect
3. Clean
4. Transform
5. Analyze
The Data Workbench
Pandas is the core environment for managing tabular data, allowing seamless transition from raw files to clean datasets.
Supported Formats
First four commands
import pandas as pd
df = pd.read_csv("scores.csv")
df.head()
df.info()
CMSC320 · Intro to Data Science
Tabular Data: Key Concept
Tabular structured format is essential for both Pandas and SQL.
Analysis & Visualization
Tabular structured formats simplify:
Exploration: Find data patterns easily
Cleaning: Handle and filter rows/columns
Plotting: Create streamlined visual charts
Shared Core Operations
Pandas & SQL share parallel operations:
Select: Slicing and filtering data
Join: Merging separate datasets
Aggregate: Grouping and summarizing
6
1. SELECT & SLICING
Select only some of the rows, or some of the columns, or a combination from a DataFrame
Original Dataset
ID | age | wgt_kg | hgt_cm |
1 | 12.2 | 42.3 | 145.1 |
2 | 11.0 | 40.8 | 143.8 |
3 | 15.6 | 65.3 | 165.3 |
4 | 35.1 | 84.2 | 185.8 |
Column Slicing
Only columns�ID and age
ID | age |
1 | 12.2 |
2 | 11.0 |
3 | 15.6 |
4 | 35.1 |
Row Filtering
Only rows with�wgt_kg > 41
ID | age | wgt | hgt |
1 | 12.2 | 42.3 | 145.1 |
3 | 15.6 | 65.3 | 165.3 |
4 | 35.1 | 84.2 | 185.8 |
Combined Slice
Both conditions:�Columns & Rows
ID | age |
1 | 12.2 |
3 | 15.6 |
4 | 35.1 |
2. AGGREGATE/REDUCE
Combine values across a column into a single value
7
ID | age | wgt_kg | hgt_cm |
1 | 12.2 | 42.3 | 145.1 |
2 | 11.0 | 40.8 | 143.8 |
3 | 15.6 | 65.3 | 165.3 |
4 | 35.1 | 84.2 | 185.8 |
SUM
SUM(wgt_kg^2 - hgt_cm)
73.9 | 232.6 | 640.0 |
MAX
35.1 | 84.2 | 185.8 |
14167.66 |
What about ID/Index column?
Usually not meaningful to aggregate across it
May need to explicitly add an ID column
8
3. MAP
Apply a function to every row, possibly creating more or fewer columns
Original Dataset
ID | Address |
1 | College Park, MD, 20742 |
2 | Washington, DC, 20001 |
3 | Silver Spring, MD, 20901 |
Mapped (Split Columns)
ID | City | State | Zip Code |
1 | College Park | MD | 20742 |
2 | Washington | DC | 20001 |
3 | Silver Spring | MD | 20901 |
Alternative Variations
Some variations allow one row to generate multiple rows in the output (commonly referred to as "flatmap").
9
4. GROUP BY
Group tuples together by column/dimension
Original Dataset
ID | A | B | C |
1 | foo | 3 | 6.6 |
2 | bar | 2 | 4.7 |
3 | foo | 4 | 3.1 |
4 | foo | 3 | 8.0 |
5 | bar | 1 | 1.2 |
6 | bar | 2 | 2.5 |
7 | foo | 4 | 2.3 |
8 | foo | 3 | 8.0 |
By 'A'
A = foo
ID | B | C |
1 | 3 | 6.6 |
3 | 4 | 3.1 |
4 | 3 | 8.0 |
7 | 4 | 2.3 |
8 | 3 | 8.0 |
A = bar
ID | B | C |
2 | 2 | 4.7 |
5 | 1 | 1.2 |
6 | 2 | 2.5 |
4. GROUP BY
Group tuples together by column/dimension
10
ID | A | B | C |
1 | foo | 3 | 6.6 |
2 | bar | 2 | 4.7 |
3 | foo | 4 | 3.1 |
4 | foo | 3 | 8.0 |
5 | bar | 1 | 1.2 |
6 | bar | 2 | 2.5 |
7 | foo | 4 | 2.3 |
8 | foo | 3 | 8.0 |
By ‘B’
ID | A | C |
5 | bar | 1.2 |
B = 1
ID | A | C |
2 | bar | 4.7 |
6 | bar | 2.5 |
ID | A | C |
3 | foo | 3.1 |
7 | foo | 2.3 |
ID | A | C |
1 | foo | 6.6 |
4 | foo | 8.0 |
8 | foo | 8.0 |
B = 3
B = 2
B = 4
4. GROUP BY
Group tuples together by column/dimension
11
ID | A | B | C |
1 | foo | 3 | 6.6 |
2 | bar | 2 | 4.7 |
3 | foo | 4 | 3.1 |
4 | foo | 3 | 8.0 |
5 | bar | 1 | 1.2 |
6 | bar | 2 | 2.5 |
7 | foo | 4 | 2.3 |
8 | foo | 3 | 8.0 |
By ‘A’, ‘B’
ID | C |
5 | 1.2 |
A = bar, B = 1
ID | C |
2 | 4.7 |
6 | 2.5 |
ID | C |
3 | 3.1 |
7 | 2.3 |
ID | C |
1 | 6.6 |
4 | 8.0 |
8 | 8.0 |
A = foo, B = 3
A = bar, B = 2
A = foo, B = 4
5. GROUP BY AGGREGATE
Compute one aggregate per group
12
ID | A | B | C |
1 | foo | 3 | 6.6 |
2 | bar | 2 | 4.7 |
3 | foo | 4 | 3.1 |
4 | foo | 3 | 8.0 |
5 | bar | 1 | 1.2 |
6 | bar | 2 | 2.5 |
7 | foo | 4 | 2.3 |
8 | foo | 3 | 8.0 |
Group by ‘B’
Sum on C
ID | A | C |
5 | bar | 1.2 |
B = 1
ID | A | C |
2 | bar | 4.7 |
6 | bar | 2.5 |
ID | A | C |
3 | foo | 3.1 |
7 | foo | 2.3 |
ID | A | C |
1 | foo | 6.6 |
4 | foo | 8.0 |
8 | foo | 8.0 |
B = 3
B = 2
B = 4
Sum (C) |
1.2 |
B = 1
B = 3
B = 2
B = 4
Sum (C) |
22.6 |
Sum (C) |
7.2 |
Sum (C) |
5.4 |
5. GROUP BY AGGREGATE
Final result usually seen as a table
13
ID | A | B | C |
1 | foo | 3 | 6.6 |
2 | bar | 2 | 4.7 |
3 | foo | 4 | 3.1 |
4 | foo | 3 | 8.0 |
5 | bar | 1 | 1.2 |
6 | bar | 2 | 2.5 |
7 | foo | 4 | 2.3 |
8 | foo | 3 | 8.0 |
Group by ‘B’
Sum on C
Sum (C) |
1.2 |
B = 1
B = 3
B = 2
B = 4
Sum (C) |
22.6 |
Sum (C) |
7.2 |
Sum (C) |
5.4 |
B | SUM(C ) |
1 | 1.2 |
2 | 7.2 |
3 | 22.6 |
4 | 5.4 |
14
6. UNION / INTERSECTION / DIFFERENCE
Set operations – only if the two tables have identical attributes/columns
ID | A | B | C |
1 | foo | 3 | 6.6 |
2 | bar | 2 | 4.7 |
3 | foo | 4 | 3.1 |
4 | foo | 3 | 8.0 |
∪
ID | A | B | C |
5 | bar | 1 | 1.2 |
6 | bar | 2 | 2.5 |
7 | foo | 4 | 2.3 |
8 | foo | 3 | 8.0 |
ID | A | B | C |
1 | foo | 3 | 6.6 |
2 | bar | 2 | 4.7 |
3 | foo | 4 | 3.1 |
4 | foo | 3 | 8.0 |
5 | bar | 1 | 1.2 |
6 | bar | 2 | 2.5 |
7 | foo | 4 | 2.3 |
8 | foo | 3 | 8.0 |
Key Behavioral Insights (These operations treat tables like sets of rows.)
Intersection (common rows) → keeps rows that appear in both tables.
Set Difference EXCEPT/MINUS→ keeps rows that appear in one table but not the other.
Note: Results can change depending on whether an ID column is included. Two rows with the same data but different IDs may be treated as different rows.
13
7. MERGE OR JOIN
Combine rows/tuples across two tables if they have the same key
15
ID | A | B |
1 | foo | 3 |
2 | bar | 2 |
3 | foo | 4 |
4 | foo | 3 |
ID | C |
1 | 1.2 |
2 | 2.5 |
3 | 2.3 |
5 | 8.0 |
ID | A | B | C |
1 | foo | 3 | 1.2 |
2 | bar | 2 | 2.5 |
3 | foo | 4 | 2.3 |
⨝
What about IDs not present in both tables?
Often need to keep them around
Can “pad” with NaN
7. MERGE OR JOIN
Combine rows/tuples across two tables if they have the same key
Outer joins can be used to ”pad” IDs that don’t appear in both tables
Three variants: LEFT, RIGHT, FULL
SQL Terminology – pandas has these operations as well
16
ID | A | B |
1 | foo | 3 |
2 | bar | 2 |
3 | foo | 4 |
4 | foo | 3 |
ID | C |
1 | 1.2 |
2 | 2.5 |
3 | 2.3 |
5 | 8.0 |
ID | A | B | C |
1 | foo | 3 | 1.2 |
2 | bar | 2 | 2.5 |
3 | foo | 4 | 2.3 |
4 | foo | 3 | NaN |
5 | NaN | NaN | 8.0 |
⟗
17
Pandas First Steps: Install & Import
01 / Terminal System Install Open terminal and run either command:
$ conda install pandas
# OR
$ pip install pandas
02 / Jupyter Notebook Setup Run inside notebook cells. The ! prefix executes as terminal shell:
!pip install pandas
03 / Python
Import & Verify
Import as pd (standard alias) and print version to verify:
import pandas as pd
print(pd.__version__)
Common Pandas Tasks and Workflow
1
Loading data: CSV, Excel, databases
2
Inspecting data: First few rows, column names, data types
3
Cleaning data
Handle missing values • Fix data types • Remove duplicates
4
Filtering & sorting
Select rows/columns • Apply conditions
5
Aggregation: Mean, median, count, group by categories
Pandas Key Data Structures
Core components of Pandas: Series & DataFrames
Visual Concept
Key Idea:
• Series is the fundamental building block.
• DataFrame is a collection of Series sharing an index.
01 / The Series
1D Labeled Array
Common Operations:
sum(), count(), unique()
02 / The DataFrame
2D Labeled Table
Data Access:
Columns accessed by name, rows accessed by index (less common).
Pandas I/O: Reading & Writing Data
Easily import external datasets and export processed results across common formats
Reading Data
# Read CSV file
df = pd.read_csv("data.csv")
# Read Excel file (XLS / XLSX)
df = pd.read_excel("data.xlsx")
# Read text file (whitespace-separated)
df = pd.read_csv("data.txt", sep="\s")
# Read JSON file
df = pd.read_json("data.json")
Key Idea: Pandas can load data from multiple file formats using the file path as input.
Outputting Data
# Write DataFrame to CSV
df.to_csv("out.csv", index=False)
# Write DataFrame to Excel
df.to_excel("out.xlsx", index=False)
# Write text file (space-separated)
df.to_csv("out.txt", sep=" ")
# Write DataFrame to JSON
df.to_json("out.json")
Key Idea: Use built-in to_*() methods on Series or DataFrames to export data smoothly.
Pandas Pipeline
Read➔Write
Reading data from a CSV file
21
df = pd.read_csv('dataset.csv')
Load a CSV file into a Pandas DataFrame:
*** If the data contains only one column and you specify squeeze=True, pandas will convert the result to a Series.
Basic Operations: Exploring Data
Row Inspection
# Display First 5 rows
df.head()
# Display Last 3 rows
df.tail(n=3)
Specify the number of rows through the n argument (the default is 5).
Schema & Metadata
# Data types
df.dtypes
# Column names
df.columns
# Overview of columns & types
df.info()
Stats & Dimensions
# Summary statistics
df.describe()
Prints count, mean, std, range, and quartiles.
# Shape (rows, columns)
df.shape
df.shape[0]: Rows only
df.shape[1]: Columns only
Basic Operations: Selecting & Modifying Data
Selecting Data
# Column Selection (Series / DataFrame)
df["Age"] or df[["Name", "City"]]
# Row Selection by Index
df.iloc[0] # first row
df.iloc[1:3] # rows 1-2
# Row Selection by Condition
df[df["Age"] > 30]
Access Pattern:
dataframe["column_name"] → accesses a column
Modifying & Arithmetic
# Create New Columns
df["new_col"] = df["col1"] + df["col2"]
df["new_col"] = df["col1"] - df["col2"]
# Modify an Existing Column
df["Age"] = df["Age"] + 1
Key Idea:
Pandas supports vectorized operations; mathematical applications automatically apply to the entire column.
24
Applying Functions Directly to a DataFrame
Column-Wise Operation
You can apply a function or method to a DataFrame column, and pandas will operate on the values in that column.
SYNTAX PATTERN
dataframe[column_name].function()
EXAMPLE
df["age"].sum()
Filtering in Pandas
Focus on specific subsets of your data
1. Column Filtering
Select specific columns by name using basic selection:
df[['col1']] or df[['col1', 'col2']]
Key Benefits:
2. Row Filtering
Select rows that satisfy a condition using Boolean Indexing:
df[df['col'] > value]
Key Benefits:
26
Filtering in Pandas cont.
How to focus on specific columns and extract rows based on conditions
1. Column Filtering
Extract specific columns by passing one or more column names. This helps focus on relevant features and reduces memory usage.
# Create sample DataFrame
df = pd.DataFrame({
'name': ['Alice', 'Bob', 'Charlie'],
'age': [25, 30, 35],
'city': ['NY', 'LA', 'Chicago']
})
# Select specific columns
df_cols = df[['name', 'age']]
2. Row Filtering (Boolean Indexing)
Select rows by passing a condition inside square brackets. Pandas keeps the rows where the condition is True.
Syntax: df[boolean_condition]
Example: df[df['Age'] > 29]
Next Step
What about multiple conditions?
27
Filtering rows
Keep rows where a condition is True
name
major
score
Ana
CS
88
Ben
Math
75
Mina
CS
92
Leo
InfoSci
NaN
Sara
CS
81
df[df['score'] > 80]
name
major
score
Ana
CS
88
Mina
CS
92
Sara
CS
81
Boolean mask idea
df['score'] > 80
# True, False, True, False, True
CMSC320 · Intro to Data Science
Counting & Aggregating in Pandas
Essential statistical methods for summarizing Series and DataFrames
1. Frequency Counts
Count unique values in categorical data. Returns a Series sorted descending by default.
df["column"].value_counts()
Expected Output:
Method | Action | Works On |
.sum() | Sum of values | DF/Series |
.mean() | Average | DF/Series |
.count() | Non-NA count | DF/Series |
.size() | All rows count | GroupBy |
.min()/.max() | Min/Max | DF/Series |
.describe() | Summary stats | DF/Series |
Filtering + Counting: Filter rows first, then count values in a selected column.
df[df['Age'] > 25]['City'].value_counts()
Applying Aggregation Functions Directly
Apply key statistical methods directly on a DataFrame or Series.
Scenario 1
On Entire DataFrame (Numeric Columns Only)
df.mean() # Mean of all numeric columns
df.max() # Max of all numeric columns
Scenario 2
On a Single Column (Series)
df['Price'].sum() # Sum of 'Price' column
df['Age'].std() # Standard deviation of 'Age'
Scenario 3Next Topic
On Grouped Data
df.groupby('Category')['Price'].mean()
Interactive Example
import pandas as pd
# Sample DataFrame
data = {'Price': [10, 15, 20], 'Quantity': [3, 2, 5]}
df = pd.DataFrame(data)
# Direct aggregations
print("Sum of columns:")
print(df.sum())
# Output: Price 45, Quantity 10
print("Mean of 'Price':")
print(df['Price'].mean())
# Output: 15.0
Key Takeaway:
Applying methods directly to a DataFrame aggregates all numeric columns, while specifying a column like ['Price'] targets only that Series.
Filtering Data & Applying Statistical Functions
df[df[condition]][column].statistics_function()
01
Filter Rows
Applies a boolean condition to filter the rows of the DataFrame.
df[df[condition]]
02
Select Column
Extracts the target column (Series) for the statistical calculation.
[column]
03
Apply Statistic
Computes the metric (mean, sum, max, min, std, etc.) on the column.
.statistics_function()
Example Find the Mean of 'Number' where Age > 25
31
Grouping Data (Groupby)
split → apply → combine
df.groupby('group_col')['target_col'].mean()
EXAMPLE: AVERAGE SCORE PER MAJOR
df.groupby('Major')['Score'].mean()
Syntax structure: [Splitting Phase] → [Target Selection (Optional)] → [Aggregation Function]
Core idea: split rows into groups, apply a summary, combine the result
01. Split
Create one group for each unique value in the grouping column.
02. Select
Choose the column you want to summarize within each group. This step is optional.
03. Apply & Combine
Apply a statistic (mean, sum, count, etc.) to each group and return a smaller table.
major
score
CS
88
Math
75
CS
92
InfoSci
NaN
CS
81
major
mean_score
CS
87.0
Math
75.0
InfoSci
NaN
One output row per group
32
GroupBy: Common Usage Patterns
df.groupby('group_col')['target_col'].mean()
1. Single Column
Group rows based on unique values in a single column.
df.groupby('column_name')
Question: average score for each major
df.groupby('major')['score'].mean()
2. Multiple Columns
Group by multiple hierarchy levels using a list of columns.
df.groupby(['col1', 'col2'])
Question: average score for each major-year pair
df.groupby(['major','year'])['score'].mean()
3. Group + Aggregate
MOST COMMON PATTERN
[col] extracts column before aggregating.
df.groupby('cat')['val'].mean() → one col
df.groupby('cat').mean() → all numeric
Question: average score & hours per major
df.groupby('major')[['score','hours']].mean()
Remember: groupby() groups rows first; column selection and aggregation happen afterwards for optimal performance.
Example: Grouping Data (Groupby)
33
1. group by “order”
2. Apply “Sum” to each group
3. Combine the result
Group By - More Examples (1)
Custom Conditions
INPUT DATAFRAME (DF)
The Task
Group the rows of the DataFrame into two groups based on whether the Values >=15, and calculate the sum of the Values for each group.
SYNTAX PATTERN
RESULT OUTPUT
Group By - More Complicated Examples (2)
INPUT DATAFRAME (DF)
RESULT OUTPUT
The Task
Find the maximum Values for each Category, but only include rows where Values are less than 25.
Execution Steps
SYNTAX PATTERN
Pandas Indexing: loc vs iloc
loc : Label-Based
Selects data by explicit labels or names. Slicing is inclusive (both bounds are kept).
# df.loc[row_label, col_label]
df.loc[1, 'Age']
# Access rows with labels from index 2 to 4 and columns 'A' and 'B'
df.loc[2:4, ['A', 'B']]
iloc : Position-Based
Selects data by integer positions. Slicing is end-exclusive (upper bound excluded).
# df.iloc[row_index, col_index]
df.iloc[1, 1]
# Access rows from index 2 to 4 and columns at positions 0 and 1
df.iloc[2:5, [0, 1]]
https://pandas.pydata.org/docs/user_guide/indexing.html
37
Merge: combining tables safely
Real datasets are often spread across multiple files. Merge by a shared key.
student_id | score |
101 | 88 |
102 | 91 |
103 | 77 |
+
student_id | major |
101 | CS |
102 | Math |
104 | InfoSci |
student_id | score | major |
101 | 88 | CS |
102 | 91 | Math |
SYNTAX PATTERN & MERGE CHECK
merged = scores.merge(roster, on="student_id", how="inner")
# Check after every merge
merged.shape
merged["student_id"].is_unique
Important Tip
Always check row counts after merging. Duplicated keys can quietly create extra rows.
Visualize DataFrames
01 Pandas dataframes can be visualized using Matplotlib.
02 Plotting dataframes is a useful way to see results and extract quick patterns.
03
Install Matplotlib using conda or pip package manager.
pip/conda install matplotlib
04 Visualization helps in understanding the dataframe content efficiently.
39
Pandas:�Key�Advantages
A powerful and essential tool for data manipulation, analysis, and cleaning in Python.
01
A powerful Python library tailored for complex data tasks like analysis and cleaning.
02
Simplifies data representation, making complex data structures easier to understand.
03
Efficiently cleans messy datasets to ensure readability, structure, and relevance.
04
Increases developer productivity by significantly minimizing the amount of code required.
05
Offers highly extensive features built specifically for seamless and robust data analysis.
40
Common Beginner Mistakes
Good pandas code is usually short, checked, and readable.
Forgetting parentheses
Combine multiple conditions using parentheses:
(df["x"] > 0) & (df["y"] < 5)
Using and/or
Python logical keywords fail on Series objects.
Use & and | for Series conditions
Not checking types
Understand your data structure before analysis:
df.info() before analysis
Dropping too much
Avoid blindly removing missing records:
Investigate missingness first
CMSC320 · Intro to Data Science
41
References & Resources
Official Documentation
External & Learning Resources
The End