Module 6: Python for Data Science (Core Skills)
Module 6: Python for Data Science (Core Skills)
Introduction to Data Science โ Week 6
Python fundamentals, NumPy, and pandas for working with data
Module Overview
Python is the most widely used language in data science. This module gives students a solid
foundation in the core skills needed to work with data in Python: the language fundamentals,
the NumPy library for numerical computation, and the pandas library for tabular data. Students
will practice reading, inspecting, selecting, filtering, grouping, and summarizing data โ all
essential skills for every later stage of the data science workflow.
Learning Objectives
By the end of this module, students will be able to:
- Write basic Python code: variables, data types, lists, dictionaries, and functions.
- Use NumPy arrays for vectorized numeric computation.
- Create, inspect, and manipulate pandas Series and DataFrames.
- Read data from CSV and Excel files into pandas.
- Select, filter, sort, and group data using pandas.
- Compute summary statistics and reshape data for analysis.
Lesson 1: Python Fundamentals
You don't need to master all of Python to do data science. A small subset of the language
covers most of what you'll use day to day.
Variables and Data Types
name = "Alex" # string
age = 13 # integer
height = 1.62 # float
is_student = True # boolean
print(name, age, height, is_student)
Alex 13 1.62 True
Lists and Dictionaries
# A list is an ordered collection
scores = [85, 92, 78, 95]
print(scores[0]) # first item
print(len(scores)) # length
print(sum(scores)) # total
# A dictionary maps keys to values
person = {"name": "Alex", "age": 13, "city": "Lagos"}
print(person["name"])
85
4
350
Alex
Functions
def average(numbers):
return sum(numbers) / len(numbers)
print(average([85, 92, 78, 95]))
87.5
๐ฆ Think of it like labeled boxes: A variable is a labeled box that stores a
value. A list is a row of boxes. A dictionary is a set of boxes with labels on the front.
Functions are like little machines โ you feed something in, and they produce an output.
๐ก Key Idea: Python is designed to be readable. If your code looks
complicated, it can probably be simplified.
Lesson 2: NumPy โ Numerical Python
NumPy is the foundation of numerical computing in Python. It provides
a fast, efficient array type and a large collection of mathematical operations.
Creating Arrays
import numpy as np
a = np.array([1, 2, 3, 4, 5])
b = np.array([[1, 2, 3], [4, 5, 6]]) # 2D array
print(a)
print(b.shape) # (2, 3)
print(a.mean())
print(a.std())
[1 2 3 4 5]
(2, 3)
3.0
1.4142135623730951
Vectorized Operations
a = np.array([1, 2, 3, 4, 5])
print(a * 10) # multiply every element
print(a + 100) # add to every element
print(a[a > 3]) # filter elements greater than 3
[10 20 30 40 50]
[101 102 103 104 105]
[4 5]
โก Think of it like this: A regular Python list is like a row of boxes you
have to open one at a time. A NumPy array is like a conveyor belt โ you can apply an
operation to every box at once, instantly.
๐ก Key Idea: NumPy is much faster than plain Python lists for large numeric
data. This is why pandas is built on top of it.
Lesson 3: pandas Series and DataFrames
pandas is the workhorse library for tabular data in Python. It
provides two main data structures: Series (a 1D labeled array) and
DataFrame (a 2D labeled table).
Creating a Series
import pandas as pd
s = pd.Series([10, 20, 30, 40], index=["a", "b", "c", "d"])
print(s)
print(s["c"])
a 10
b 20
c 30
d 40
dtype: int64
30
Creating a DataFrame
data = pd.DataFrame({
"name": ["Alex", "Jordan", "Sam", "Riley"],
"age": [13, 13, 12, 14],
"score": [85, 92, 78, 95]
})
print(data)
name age score
0 Alex 13 85
1 Jordan 13 92
2 Sam 12 78
3 Riley 14 95
Inspecting a DataFrame
data.head() # first 5 rows
data.tail() # last 5 rows
data.shape # (rows, columns)
data.columns # column names
data.dtypes # data types
data.info() # summary
data.describe() # numeric summary statistics
๐ Think of it like this: A Series is like a single column in a spreadsheet.
A DataFrame is like the whole spreadsheet โ rows, columns, labels, and all.
Lesson 4: Reading and Writing Data
Most data science work starts with loading data from files. pandas makes this trivial.
Reading Files
import pandas as pd
# CSV
data = pd.read_csv("data.csv")
# Excel
data = pd.read_excel("data.xlsx", sheet_name="Sheet1")
# With options
data = pd.read_csv("data.csv", sep=";", na_values=["NA", "?"])
Writing Files
data.to_csv("clean_data.csv", index=False)
data.to_excel("clean_data.xlsx", index=False)
๐ก Key Idea: CSV is the most common format for sharing data. Excel is common
in business settings. Both are supported natively by pandas.
โ ๏ธ Watch Out! When reading CSVs, always check:
- Did the column types come through correctly? (e.g., numbers might be read as strings.)
- Are there missing values? (Use
data.isnull().sum().)
- Did the separator get parsed correctly? (Comma vs. semicolon vs. tab.)
Lesson 5: Selecting and Filtering Data
Selecting Columns
data["name"] # single column (Series)
data[["name", "score"]] # multiple columns (DataFrame)
Selecting Rows
data.loc[0] # by index label
data.iloc[0] # by position
data.loc[0:2] # rows 0 to 2 (inclusive)
data.iloc[0:3] # first 3 rows (exclusive)
Filtering
data[data["score"] > 85]
data[(data["age"] == 13) & (data["score"] > 80)]
data[data["name"].isin(["Alex", "Sam"])]
Sorting
data.sort_values("score") # ascending
data.sort_values("score", ascending=False) # descending
๐ Think of it like a search engine: Filtering a DataFrame is like searching
your data for a specific condition. You write the "query" (e.g., score > 85), and pandas
returns only the matching rows.
๐ก Key Idea: loc and iloc are two ways to select
rows. Use loc when you know the label; use iloc when you know the
position.
Lesson 6: Grouping and Aggregation
Grouping is one of the most powerful pandas operations. It splits
your data into groups, applies a function to each group, and combines the results โ often
called split-apply-combine.
Basic GroupBy
data.groupby("class")["score"].mean()
class
A 91.5
B 82.0
C 74.2
Name: score, dtype: float64
Multiple Statistics at Once
data.groupby("class")["score"].agg(["mean", "median", "std", "count"])
Grouping by Multiple Columns
data.groupby(["class", "gender"])["score"].mean()
Cross-Tabulation
pd.crosstab(data["gender"], data["class"])
๐งฉ Think of it like sorting laundry: You dump all your clothes on the floor,
split them into piles by color (or type), apply the same action to each pile (fold or wash),
and then put everything back together โ neatly organized. That's exactly what groupby does.
๐ก Key Idea: Groupby often reveals patterns that are invisible in the overall
data. Always check subgroup differences before drawing conclusions.
Lesson 7: Reshaping and Combining Data
Pivot Tables
data.pivot_table(
values="score",
index="class",
columns="gender",
aggfunc="mean"
)
Merging Two DataFrames
# Similar to SQL JOIN
merged = pd.merge(students, scores, on="student_id", how="inner")
# Common merge options:
# how="inner" -> only matching rows
# how="left" -> all rows from the left table
# how="right" -> all rows from the right table
# how="outer" -> all rows from both tables
Concatenating DataFrames
# Stack two DataFrames with the same columns
combined = pd.concat([df1, df2], ignore_index=True)
๐ก Key Idea: Merging is like joining two puzzle pieces. You specify the key
column (the "glue"), and pandas assembles the pieces.
โ ๏ธ Watch Out! When merging, always check:
- Are the key columns the same data type? (Numbers vs. strings can cause silent mismatches.)
- Are there duplicate keys? (One-to-many joins can multiply your rows.)
- How many rows did you have before and after? (A quick sanity check.)
Hands-On Lab: Load, Explore, and Summarize a Dataset
Goal: Practice the core pandas skills by working with a real dataset.
Instructions
- Download a small public dataset (e.g., the Titanic dataset from Kaggle).
- Open it in Jupyter Notebook or Google Colab.
- Complete the following tasks:
- Load the data into a DataFrame and inspect it with
head(), info(), and describe().
- Select only the rows where the target column meets a condition (e.g., survival = 1).
- Select only the columns relevant to your question.
- Sort the data by a numeric column.
- Use
groupby to compare a numeric variable across categories (e.g., survival rate by passenger class).
- Create a pivot table to explore two dimensions at once.
- Merge the dataset with a second small DataFrame (or create a fake "mapping" table to practice).
- Write a short summary (1 page) of what you found:
- What does the dataset contain?
- What patterns did you notice?
- Which pandas operations were most useful?
Submission
Your Jupyter Notebook (with code and output) + a 1-page summary.
Assessment for Module 6
- Quiz (10 questions): Covers Python basics, NumPy, pandas Series/DataFrames, filtering, and groupby.
- Lab: Graded on correct use of pandas operations and clarity of the summary.
- Participation: Contribution to the group activity and discussion prompts.
Key Terms
- Python โ a popular general-purpose programming language.
- NumPy โ a library for efficient numerical computation in Python.
- Array โ a NumPy data structure for numeric data.
- pandas โ a Python library for tabular data analysis.
- Series โ a one-dimensional labeled array in pandas.
- DataFrame โ a two-dimensional labeled table in pandas.
- loc โ label-based row selection in pandas.
- iloc โ position-based row selection in pandas.
- groupby โ split-apply-combine operation for grouped analysis.
- pivot_table โ a pandas method for creating spreadsheet-style summaries.
- merge โ join two DataFrames on one or more keys.
Discussion Prompts
- Why do you think Python became the dominant language in data science?
- What's the difference between a NumPy array and a Python list? When would you use each?
- What's the difference between a pandas Series and a DataFrame?
- Why is groupby so powerful for exploratory analysis?
- What could go wrong if you merge two DataFrames without checking the keys?
Further Reading
- Wes McKinney, Python for Data Analysis (3rd ed.) โ chapters 3โ5
- Official NumPy and pandas documentation (both are excellent)
- Python Data Science Handbook by Jake VanderPlas (free online)
- Kaggle Learn: "Python" and "Pandas" micro-courses
- Real Python tutorials on pandas and NumPy
๐ก Instructor Note: This is the most hands-on module of the course so far.
Students should spend at least two hours typing code themselves โ not just reading it.
Provide a scaffolded notebook with TODO cells so students can practice incrementally. Emphasize
that reading pandas documentation is a core skill, not a sign of weakness.