Week 1 - Data Analytics in Context
1. Learning Objectives
By the end of this lecture, students should be able to:
Understand what a data ecosystem is in a business context
Identify types of data used in analytics
Explain the objectives of data analysis
Relate analytics concepts to real business decisions
2. What Is a Data Ecosystem?
A data ecosystem refers to the complete environment in which data is:
1. Generated
2. Collected
3. Stored
4. Processed
5. Analysed
6. Used for decision-making
Business Example
A retail company’s ecosystem may include:
Point-of-Sale systems (transactions)
CRM systems (customer data)
Social media (sentiment data)
Inventory systems
Analytics tools (Python, dashboards)
3. Components of a Data Ecosystem
Explain each layer clearly:
1. Data Sources
o Internal: sales, HR, finance
o External: market data, APIs, social media
2. Data Storage
o Files (CSV, Excel, JSON)
1. A JSON file (.json) is a lightweight, text-based, and human-readable format used
for storing and transporting structured data, typically between a server and a
web application
o Databases (SQL)
o Cloud storage
3. Data Processing
o Cleaning
o Transformation
o Integration
4. Analytics & Modelling
o Descriptive statistics
o Predictive models
o Optimization (In the context of Business Analytics (Analytics and Modelling),
optimization is a quantitative decision-making approach that identifies the most
efficient, cost-effective, or profitable solution from a set of feasible alternatives, subject
to organizational constraints such as budget, capacity, time, or resources)
5. Decision & Action
o Business insights
o Strategy formulation
4. Types of Data
A. By Structure
Type Description Examples
Structured Tabular, fixed schema CSV, Excel
Semi-Structured Flexible schema JSON, XML
Unstructured No schema Text, images
Schema: Logical structure of data, defining how data is organized, stored, and related.
B. By Nature
Numerical: Sales, revenue
Categorical: Gender, product type
Time-series: Monthly sales
Textual: Reviews, feedback
5. Data Analysis Objectives
Explain the four levels using business language:
1. Descriptive Analytics
o What happened?
o Example: Monthly sales report
2. Diagnostic Analytics
o Why did it happen?
o Example: Sales dropped due to supply issues
3. Predictive Analytics
o What will happen?
o Example: Forecast next quarter’s sales
4. Prescriptive Analytics
o What should we do?
o Example: Optimal pricing strategy
6. Role of Python in Business Analytics
Python is used because it:
Is easy to read and learn
Has powerful data libraries
Integrates well with files and databases
Scales from small to large datasets
File Structures, Formats, and Python Libraries for Data Analysis
1. Learning Objectives
Students will be able to:
Understand common business data file formats
Identify key Python analytics libraries
Load and inspect datasets using Python
2. Common File Structures in Business Analytics
A. CSV (Comma-Separated Values)
Most common analytics format
Lightweight and fast
Example: sales_data.csv
B. Excel Files
Business-friendly
Multiple sheets
Example: [Link]
C. JSON Files
Semi-structured
Widely used in APIs
Example: [Link]
3. Core Python Libraries for Analytics
Introduce conceptually before coding:
Library Purpose
pandas Data manipulation
numpy Numerical operations
matplotlib Visualization
seaborn Statistical visualization
openpyxl Excel file handling
4. Installing Required Libraries
Use VS Code Terminal:
pip install pandas numpy matplotlib seaborn openpyxl
Explain:
pip = Python package manager
Libraries extend Python’s capability
5. Introduction to pandas
Explain the DataFrame concept:
Tabular structure (rows & columns)
Similar to Excel or SQL tables
Lab 1: Environment Setup and Loading CSV Files
Step 1: Set Up Visual Studio Code
1. Install Python extension
2. Select Python interpreter (Select from Bottom Left)
3. Create a project folder
4. Create file: lab1_csv.py
Step 2: Import Libraries
import pandas as pd
Step 3: Load a CSV File
data = pd.read_csv("[Link]")
Explain:
File must be in the same folder
Otherwise, provide a full path
Step 4: Inspect the Data
[Link]()
[Link]()
[Link]()
type(data) #DataFrame
Explain:
head() → first 5 rows
info() → structure & missing values
describe() → summary statistics
Step 5: Simple Exploration
print([Link])
print([Link])
Part A: JSON Files
json_data = pd.read_json("[Link]")
json_data.head()
Explain:
JSON is dictionary-like
pandas automatically normalises simple structures
Part B: Excel Files
excel_data = pd.read_excel("[Link]")
excel_data.head()
Multiple sheets:
excel_data = pd.read_excel("[Link]", sheet_name="Sheet1")
Part C: Comparing File Types
Discuss:
CSV: fastest, simplest
Excel: business reporting
JSON: web and APIs
Week 2 – Python Libraries for Data Analysis
Arrays and Vectorised Operations
1. Lecture Objectives
By the end of this lecture, students will be able to:
Understand what NumPy arrays are and why they are used
Create and manipulate 1D and 2D arrays
Perform vectorised operations
Explain why NumPy is essential for business analytics performance
2. Why NumPy in Business Analytics?
Begin with a business framing.
In business analytics, we often deal with:
Thousands or millions of numerical values
Calculations such as totals, averages, growth rates
Performance-sensitive operations
Python lists are slow for numerical computation.
NumPy arrays are fast, efficient, and optimised.
3. Importing NumPy (Standard Convention)
import numpy as np
Explain:
np is a convention used globally
Makes code concise and readable
4. Python List vs NumPy Array (Conceptual Difference)
Python List
sales = [100, 200, 300]
NumPy Array
sales_array = [Link]([100, 200, 300])
Key Differences
Aspect List NumPy Array
Data type Mixed Homogeneous
Speed Slower Faster
Analytics use Limited Core analytics
5. Creating NumPy Arrays
5.1 One-Dimensional Array (1D)
revenue = [Link]([500, 700, 900, 1100])
Explain:
Represents a single variable (e.g., monthly revenue)
5.2 Two-Dimensional Array (2D)
sales_data = [Link]([
[1, 500],
[2, 700],
[3, 900]
])
Explain:
Rows = observations
Columns = variables
Similar to a table
6. Inspecting Arrays
sales_data.shape
sales_data.ndim
sales_data.dtype
Explain each:
shape → rows × columns
ndim → number of dimensions
dtype → data type (important for analytics)
7. Vectorized Operations (Core Concept)
In Python, a vector is typically represented as a one-dimensional array (specifically a [Link])
using the NumPy library.
In the world of Python data science, [Link] is essentially the "source of truth." It is the core
object of the NumPy library, representing a fast, flexible, and memory-efficient N-dimensional array.
Vectorization means:
Performing operations on entire arrays
Avoiding explicit Python loops
Think of it as a grid of values, all of the same type, indexed by a tuple of non-negative integers.
Key Characteristics
Homogeneous: Unlike Python lists, every element in an ndarray must be of the same data type
(e.g., all integers or all floats). This allows NumPy to perform lightning-fast operations.
Fixed Size: Once created, you can't change the size of an array. If you "append" an element,
NumPy actually creates a brand-new array and deletes the old one.
Vectorization: This is the "magic" part. You can perform operations on the entire array at once
without writing for loops, which is significantly faster in Python.
Understanding the Structure
The "N" in ndarray stands for any number of dimensions. Here is how they are usually visualized:
Dimensio Common Name Structure
n
1D Vector A single row of data.
2D Matrix A grid with rows and columns.
3D Tensor A stack of matrices (like a book of data grids).
Important Attributes
When you are working with an ndarray, you will frequently check these three properties to understand
your data:
1. .shape: A tuple representing the size of each dimension. For a 2D matrix with 3 rows and 4
columns, the shape is (3, 4).
2. .dtype: Tells you the data type of the elements (e.g., int64, float32).
3. .ndim: The number of axes (dimensions) the array has.
Why not just use a Python List?
If you're wondering why we don't just use [[1, 2], [3, 4]], it comes down to performance. Python lists are
arrays of pointers to objects scattered in memory. A [Link] is a contiguous block of memory.
This allows your computer's CPU to cache the data more effectively and perform faster mathematical
operations.
While a standard Python list can store a sequence of numbers, NumPy arrays are the standard for
numerical computing because they are more efficient and allow for high-performance mathematical
operations.
Traditional Loop (Not Recommended)
revenue = [500, 700, 900, 1100]
updated_revenue = []
for value in revenue:
updated_revenue.append(value * 1.10)
Vectorized NumPy Operation (Recommended)
revenue = [Link]([500, 700, 900, 1100])
updated_revenue = revenue * 1.10
Explain clearly:
No loops
Faster execution
Cleaner code
Industry standard
8. Common Vectorised Operations
import numpy as np
revenue = [Link]([500, 700, 900, 1100])
revenue + 100
revenue * 1.05
[Link]()
revenue - [Link]()
Business interpretation:
Add fixed cost
Apply growth rate
Center data around average
1. Creating an Array
You can convert a standard Python list into a [Link] using the [Link]() function.
import numpy as np
# Creating a 2D array (a matrix)
my_list = [[1, 2, 3], [4, 5, 6]]
arr = [Link](my_list)
print(arr)
print(f"Shape: {[Link]}") # Output: (2, 3) .shape tells you the dimensions of an array.
#Simple Vectorization
arr_plus_10 = arr + 10
print(arr_plus_10)
arr_times_2 = arr * 2
print(arr_times_2)
arr_squared = arr ** 2 #Square every element
print(arr_squared)
2. The Power of Vectorization
In standard Python, if you wanted to add 10 to every number in a list, you would have to loop through
every single item. With NumPy, you treat the array like a single mathematical object. This is called
vectorization.
The "Pythonic" List way (Slow):
Python
numbers = [1, 2, 3, 4, 5]
plus_ten = [x + 10 for x in numbers]
The NumPy way (Fast & Clean):
Python
arr = [Link]([1, 2, 3, 4, 5])
plus_ten = arr + 10 # This happens instantly across the whole array
3. Array-to-Array Math
You can also perform operations between two arrays of the same shape. NumPy matches them up
element-by-element.
Operation Syntax Result
Addition a+b Adds corresponding elements
Multiplication a*b Multiplies corresponding elements
Dot Product a@b Matrix multiplication
Note: If you try to add two arrays of different shapes, NumPy will try to "stretch" the smaller one to fit
the larger one. This is a powerful feature called Broadcasting.
For the dot product, inner dimensions must match. The Columns in the first matrix must be equal to the
rows in the second matrix (since multiplication is Row * column in a matrix).
Step 1: Write the Matrices Clearly
Matrix A (my_list1)
A=
[ 14 2 3
5 6 ]
Matrix B (my_list2.T)
Original:
[ 14 2 3
5 6 ]
Transpose:
[ ]
1 4
B= 2 5 Step 2: Matrix Multiplication Rule
3 6
Each element in the result matrix is:
Row of A ⋅Column of BThat is, row × column (dot product).
Step-by-Step Calculations
Result will be a 2 × 2 matrix.
🔹 Element (1,1)
Row 1 of A × Column 1 of B
¿¿(1×1)+(2× 2)+(3 ×3)¿ 1+4 +9=14🔹 Element (1,2)
Row 1 of A × Column 2 of B
¿¿(1× 4)+(2× 5)+(3 ×6)¿ 4 +10+18=32🔹 Element (2,1)
Row 2 of A × Column 1 of B
¿¿(4 × 1)+(5× 2)+(6 ×3)¿ 4 +10+18=32🔹 Element (2,2)
Row 2 of A × Column 2 of B
¿¿(4 × 4)+(5× 5)+(6 × 6)¿ 16+25+ 36=77 Final Result
[ 1432 3277]
Basic Array Initialization
Often, you don't have the data yet and need to create a "placeholder" array. Here are the most common
ways to do that:
[Link]((3, 4)): Creates a 3x4 array filled with 0.
[Link]((2, 2)): Creates a 2x2 array filled with 1.
[Link](0, 10, 2): Creates an array from 0 to 10 with a step of 2 [0, 2, 4, 6, 8].
[Link](3, 3): Creates a 3x3 array with random floats between 0 and 1.
1. The Vector (The "What")
In NumPy, a 1-dimensional array is indeed called a vector.
It has only one axis.
Its shape is represented as a single-element tuple, like (5,).
Think of it as a simple list of numbers that lives in a single line.
2. Vectorized Operations (The "How")
This is where it gets interesting. While the name comes from "vectors," a vectorized operation can
actually be applied to arrays of any dimension (1D vectors, 2D matrices, or 3D tensors).
When we say an operation is "vectorized," it means the operation is applied to the entire array at once
(element-wise) rather than iterating through it with a manual loop in Python.
Summary Table
Term Definition Example
1D Array A data structure with one axis. [10, 20, 30]
Vector The mathematical name for a 1D array. A displacement or
force.
Vectorization Performing a calculation on all elements "at once" without arr * 2 or [Link](arr)
explicit Python loops.
Key takeaway: You can perform vectorized operations on things that aren't 1D vectors (like a 2D table or
a 3D image).
9. Aggregation Functions (Analytics-Oriented)
[Link]()
[Link]()
[Link]()
[Link]()
Relate each to business reporting:
Total sales
Average revenue
Best / worst period
Pandas Series and DataFrames
1. Lecture Objectives
By the end of this lecture, students will be able to:
Understand pandas Series and DataFrames
Create Series and DataFrames
Perform basic inspection and selection
Relate pandas objects to business datasets
2. Why pandas?
Reinforce continuity from Week 1.
NumPy → numerical computation
pandas → business data analysis
pandas builds on top of NumPy, adding:
Labels
Indexing
Tabular operations
3. Importing pandas
import pandas as pd
4. Pandas Series (One-Dimensional Labeled Data)
4.1 Creating a Series
sales = [Link]([500, 700, 900], index=["Jan", "Feb", "Mar"])
Explain:
Values + labels
Similar to a single Excel column
4.2 Accessing Series Data
sales["Jan"]
[Link]()
Business interpretation:
Access monthly sales
Compute average sales
5. Pandas DataFrame (Two-Dimensional Data)
5.1 Creating a DataFrame
data = {
"Month": ["Jan", "Feb", "Mar"],
"Revenue": [500, 700, 900],
"Cost": [300, 400, 450]
}
df = [Link](data)
Explain:
Dictionary → DataFrame
Columns represent variables
Rows represent observations
6. Inspecting a DataFrame (Critical Skill)
[Link]()
[Link]()
[Link]()
Explain each carefully:
head() → preview data
info() → data types & missing values
describe() → summary statistics
7. Selecting Data (Step-by-Step)
7.1 Selecting a Column
df["Revenue"]
7.2 Selecting Multiple Columns
df[["Revenue", "Cost"]]
7.3 Selecting Rows by Index
[Link][0]
Explain:
.loc[] is label-based
Industry-preferred method
8. Simple Calculations Using DataFrames
df["Profit"] = df["Revenue"] - df["Cost"]
Explain:
Column-wise operations
Vectorised by default
No loops required
9. Business Insight Example
df["Profit"].mean()
Interpretation:
Average profit across periods
Connect analytics to decision-making
10. Series vs DataFrame (Conceptual Summary)
Feature Series DataFrame
Dimensions 1D 2D
Use case Single variable Business dataset
Example Monthly sales Sales + cost + profit
WEEK 3: DESCRIPTIVE STATISTICS FOR BUSINESS ANALYTICS
Lecture 1: Measures of Central Tendency and Dispersion
1. Lecture Objectives
By the end of this lecture, students will be able to:
Understand why descriptive statistics are needed
Explain mean, median, and mode
Explain range, variance, and standard deviation
Interpret statistics in business contexts (e.g., salaries, sales)
2. Why Descriptive Statistics in Business?
Begin with a managerial question:
“Are employees fairly paid?”
“Is Store A performing better than Store B?”
“Is sales performance stable or volatile?”
Raw data alone cannot answer these.
Descriptive statistics summarize data into decision-ready insights.
3. Measures of Central Tendency (Location)
3.1 Mean (Average)
Concept
Arithmetic average
Sensitive to extreme values (outliers)
Formula (Conceptual – no math depth)
Mean = Sum of values / Number of values
Business Example
Average monthly salary
Average daily sales
3.2 Median (Middle Value)
Concept
Middle observation after sorting
Robust to outliers
Business Importance
Often preferred for:
o Salaries
o Income
o Property prices
Explain clearly:
“Median salary often represents a more realistic ‘typical’ employee.”
3.3 Mode (Most Frequent Value)
Concept
Value that occurs most often
Business Use
Most common salary bracket
Most frequently sold product
4. Measures of Dispersion (Spread)
4.1 Range
Range = Max − Min
Interpretation
Overall spread
Very sensitive to extreme values
4.2 Variance
Concept
Average squared deviation from the mean
Measures variability
Explain simply:
“Variance tells us how spread out the data is.”
Avoid formula-heavy explanations at this stage.
4.3 Standard Deviation (Most Important)
Concept
Square root of variance
Measured in the same units as the data
Business Interpretation
Low SD → consistent performance
High SD → volatile performance
Example:
Stable store vs fluctuating store sales
Lecture 2: Pandas Statistical Summaries
1. Lecture Objectives
By the end of this lecture, students will be able to:
Compute descriptive statistics using pandas
Use .describe() effectively
Compare groups (e.g., stores)
Translate numbers into business insights
2. Preparing the Dataset
import pandas as pd
data = pd.read_csv("[Link]")
Always reinforce:
[Link]()
[Link]()
3. Computing Measures of Central Tendency
Mean
data["Revenue"].mean()
Median
data["Revenue"].median()
Mode
data["Revenue"].mode()
Explain:
.mode() may return multiple values
This is normal in real data
4. Computing Measures of Dispersion
data["Revenue"].min()
data["Revenue"].max()
data["Revenue"].std()
data["Revenue"].var()
Business explanation:
Standard deviation tells us risk / volatility
Variance is rarely reported directly in business
5. Using .describe() (Core Skill)
[Link]()
Explain each output column:
count → non-missing values
mean → average
std → dispersion
min / max → extremes
25%, 50%, 75% → quartiles
Tell students:
“If you understand .describe(), you understand descriptive analytics.”
6. Comparing Store Sales (Group Analysis)
Assume a column Store exists.
[Link]("Store")["Revenue"].mean()
Extend:
[Link]("Store")["Revenue"].agg(["mean", "median", "std"])
Explain:
Store comparison
Performance vs consistency
Decision-making relevance
7. Interpretation Example (Teach Explicitly)
Store A has higher average sales but higher variability.
Store B has lower average sales but more stable performance.
Ask:
Which store is better?
Depends on business strategy.
LAB (Week 3): Salary Distributions & Store Sales Comparison
Lab Objectives
Students will:
Analyze salary distributions
Compare sales performance across stores
Practice interpretation, not just coding
Part A: Salary Distribution Analysis
Step 1: Load Data
salary = pd.read_csv("[Link]")
Step 2: Descriptive Statistics
salary["Salary"].describe()
Step 3: Interpretation (Mandatory)
Students must answer:
Is the salary distribution skewed?
Is the median more appropriate than the mean?
Part B: Compare Store Sales
Step 1: Group Statistics
[Link]("Store")["Revenue"].describe()
Step 2: Key Questions
Which store has higher average sales?
Which store is more consistent?
Which store would management prioritize?
Part C: Visualization (Optional but Recommended)
data["Revenue"].hist()
Explain:
Shape of distribution
Link between visuals and statistics
WEEK 4: DATA MANIPULATION WITH PANDAS
Lecture 1: Pandas Data Structures, Indexing, and Slicing
1. Lecture Objectives
By the end of this lecture, students will be able to:
Clearly distinguish Series vs DataFrames
Understand the role of the index
Select rows and columns using .loc[] and .iloc[]
Slice data safely and correctly for analysis
2. Revisiting Pandas Data Structures (Quick Recap)
Pandas Series
One-dimensional
Labeled index
Equivalent to one Excel column
import pandas as pd
sales = [Link]([500, 700, 900], index=["Jan", "Feb", "Mar"])
Pandas DataFrame
Two-dimensional
Rows and columns with labels
Equivalent to a worksheet or database table
data = pd.read_csv("[Link]")
Reinforce:
A DataFrame is a collection of Series.
3. Understanding the Index (Critical Concept)
Explain verbally before coding:
The index identifies rows
It is not the same as row number
Used for selection, alignment, and joins
[Link]
Show:
Default index (0, 1, 2, …)
Can be changed later
4. Column Selection (Foundation Skill)
Single Column
data["Revenue"]
Result:
Returns a Series
Multiple Columns
data[["Product", "Revenue"]]
Result:
Returns a DataFrame
5. Row Selection Using .loc[] (Label-Based)
Selecting a Row by Index Label
[Link][0]
Explain:
Uses index labels
Recommended for readability and safety
Selecting Multiple Rows
[Link][0:3]
Explain:
Inclusive slicing
Different from Python lists
Selecting Rows and Columns Together
[Link][0:3, ["Product", "Revenue"]]
This is a core analytics pattern.
6. Row Selection Using .iloc[] (Position-Based)
Selecting a Row by Position
[Link][0]
Explain:
Uses numerical position
Similar to NumPy indexing
Slicing Rows and Columns
[Link][0:3, 1:3]
Explain:
End index is exclusive
Use .iloc[] when position matters
7. .loc[] vs .iloc[] (Exam-Friendly Summary)
Feature .loc[] .iloc[]
Based on Labels Positions
Inclusive slicing Yes No
Business readability High Medium
Teaching rule:
Use .loc[] unless you have a strong reason not to.
Lecture 2: Filtering Data and Handling Missing Data
1. Lecture Objectives
By the end of this lecture, students will be able to:
Filter datasets using conditions
Combine multiple conditions
Identify missing values
Handle missing data appropriately
2. Why Data Manipulation Matters
Explain clearly:
“In real business data, you rarely analyze the entire dataset at once.”
Examples:
High-value customers only
Specific time periods
Cleaned data only
3. Filtering Rows with Conditions
Single Condition
high_sales = data[data["Revenue"] > 1000]
Explain:
Condition returns True/False
pandas filters rows automatically
Multiple Conditions
filtered = data[(data["Revenue"] > 1000) & (data["Store"] == "A")]
Explain:
Use & instead of and
Parentheses are mandatory
4. Filtering Using .loc[] (Best Practice)
[Link][data["Revenue"] > 1000, ["Product", "Revenue"]]
Explain:
Combines filtering + selection
Cleaner and safer syntax
5. Detecting Missing Data
Identify Missing Values
[Link]()
Count Missing Values
[Link]().sum()
Explain:
Missing values appear as NaN
Extremely common in real datasets
6. Handling Missing Data (Three Strategies)
Strategy 1: Drop Missing Values
[Link]()
Use when:
Few missing rows
Data loss is acceptable
Strategy 2: Fill Missing Values (Imputation)
data["Revenue"].fillna(data["Revenue"].mean(), inplace=True)
Use when:
Missing values are frequent
Mean represents data well
Strategy 3: Forward Fill (Time-Series Context)
[Link](method="ffill", inplace=True)
Explain:
Common in financial and operational data
7. Business Interpretation (Teach Explicitly)
Ask students:
Why are values missing?
Should they be removed or imputed?
How might this affect decisions?
This is where analytics meets judgment.
8. Data Cleaning Workflow (Recommended Pattern)
[Link]()
[Link]()
[Link]().sum()
[Link]() # or fillna()
Teach:
Data cleaning is not optional; it is analytics.
9. Lecture 2 Wrap-Up
Students can now:
Filter datasets intelligently
Handle missing values responsibly
Prepare clean data for visualization and modeling