Hiring Partners
Segilola Resources Operating LimitedTaviatech TechnologiesFCMBMTN NigeriaAdvans La Fayette Microfinance BankAboki AfricaFirst Bank of NigeriaOPay
← Python Fundamentals Level Two Β· Lesson 4 of 9

Module Three

πŸ“– Every lesson in this course is free to read right here, no account needed. Create a free account to track your progress, take the exam, and earn your certificate.
4
Module Three: Data Analysis with Pandas and NumPy

🐍 Module Three: Data Analysis with Pandas and NumPy


πŸ“– Module Introduction

Welcome, data explorer! 🌟 You have learned how to build web applications with Flask and manage databases. Now, it is time to unlock the power of data analysis. In today's world, data is everywhere β€” from sales figures to social media posts. Being able to analyse and understand data is a superpower.

In this module, you will learn two of the most important Python libraries for data analysis: NumPy (Numerical Python) and Pandas (Panel Data). NumPy provides fast mathematical operations on arrays. Pandas builds on top of NumPy and gives you easy-to-use data structures like DataFrames, which are like spreadsheets in Python.

You will learn how to load data from CSV files, clean and transform it, filter and sort it, group and aggregate it, and even create basic visualizations. By the end of this module, you will be able to take a messy dataset and turn it into meaningful insights.

Think of NumPy and Pandas as your data detective tools πŸ”. They help you find patterns, uncover secrets, and tell stories with data. Let us begin our data adventure! πŸ“Š


🎯 Learning Objectives

By the end of this module, you will be able to:

  • Explain what NumPy and Pandas are and why they are useful.
  • Create and manipulate NumPy arrays.
  • Perform basic mathematical operations with NumPy.
  • Understand Pandas Series and DataFrames.
  • Load data from CSV files into DataFrames.
  • Explore and inspect data using head(), info(), describe().
  • Filter, sort, and select data from DataFrames.
  • Handle missing data with dropna() and fillna().
  • Group and aggregate data with groupby().
  • Apply functions to data with apply() and map().
  • Create basic plots using Pandas and Matplotlib.
  • Save analysis results to CSV files.

πŸ“š Warm-up Story: Ada's Market Analysis

Ada's mother ran a small grocery store in Lagos. She kept a notebook with daily sales of different products β€” rice, beans, tomatoes, onions, and more. But it was hard to see which products sold best and on which days. Ada wanted to help her mother make better decisions.

"Mummy, I can use Python to analyse your sales data!" Ada said. She typed all the sales numbers into a CSV file. Then she used Pandas to load the data, clean it, and find the average sales per product. She even created a chart showing sales over the week.

"Wow!" her mother said. "Now I know that tomatoes sell most on Fridays and Saturdays. I will buy more tomatoes on those days!" Ada's analysis helped her mother earn more money and reduce waste.

Ada had discovered the power of data analysis. And you will learn how to do the same β€” using Python to turn raw data into useful information. Let us dive in! πŸ“ˆ


πŸ“˜ Lesson 1: What are NumPy and Pandas?

Definition: NumPy is a library for numerical computing in Python. It provides fast, multidimensional arrays and mathematical functions. Pandas is a library built on top of NumPy that provides easy-to-use data structures and data analysis tools.

Why it is important: These libraries are the foundation of data science in Python. They are used by millions of people for data cleaning, analysis, and visualization.

Simple explanation: Imagine you have a big pile of numbers. NumPy is like a super-fast calculator that can do math with all those numbers at once. Pandas is like a smart spreadsheet that organizes the numbers into rows and columns and lets you slice, dice, and analyse them easily.

Real-life example: A data scientist uses Pandas to analyse sales data and NumPy for complex calculations.

School example: You use a spreadsheet (like Excel) to track your grades; Pandas is like that but in Python.

Home example: You keep a list of your expenses in a notebook; Pandas can help you find patterns.

Nigerian example: A market analyst uses Pandas to analyse vegetable prices across different markets.

Illustration:

    NUMPY AND PANDAS
    +-------------------------------------------------+
    |  NumPy: Fast numerical arrays                   |
    |  ↓                                              |
    |  Pandas: High-level data structures (DataFrame) |
    |  ↓                                              |
    |  Data analysis, cleaning, visualization         |
    +-------------------------------------------------+
    

Mini summary: NumPy provides fast arrays for mathematical operations; Pandas provides powerful data structures for analysis.


πŸ“˜ Lesson 2: Installing NumPy and Pandas

Definition: To use these libraries, you need to install them using pip.

Why it is important: They are not built into Python, so you have to install them separately.

Simple explanation: Think of NumPy and Pandas as apps you download on your phone. You need to install them before you can use them.

Installation commands:

    pip install numpy pandas matplotlib
    

Real-life example: A developer installs these libraries before starting a data analysis project.

School example: You install a calculator app on your phone before using it.

Home example: You buy a new kitchen tool before cooking a new recipe.

Nigerian example: A data analyst in Abuja installs Pandas to analyse customer data.

Illustration:

    INSTALLATION
    +-------------------------------------------------+
    |  pip install numpy pandas matplotlib            |
    +-------------------------------------------------+
    

Mini summary: Install NumPy, Pandas, and Matplotlib using pip to get started with data analysis.


πŸ“˜ Lesson 3: Introduction to NumPy Arrays

Definition: A NumPy array is a grid of values, all of the same type, that can be efficiently computed. It is like a list, but faster and more powerful.

Why it is important: NumPy arrays are the foundation of many data science operations. They make mathematical operations fast.

Simple explanation: Think of a NumPy array as a bullet train πŸš„ compared to a regular list (which is like a bicycle). It can handle large amounts of data much faster.

How to create an array:

    import numpy as np

    # From a list
    arr = np.array([1, 2, 3, 4, 5])

    # Zeros array
    zeros = np.zeros(5)  # [0., 0., 0., 0., 0.]

    # Ones array    # [1., 1., 1.]

    # Range of numbers
    range_arr = np.arange(0, 10, 2)  # [0, 2, 4, 6, 8]

    # Random numbers
    rand_arr = np.random.rand(3)  # random numbers between 0 and 1
    

Real-life example: A scientist uses NumPy arrays to store temperature readings from sensors.

School example: You have a list of your test scores; you can convert it to a NumPy array to calculate the average.

Home example: You track your daily step count in a NumPy array.

Nigerian example: A farmer stores daily rainfall measurements in a NumPy array.

Illustration:

    NUMPY ARRAY
    +-------------------------------------------------+
    |  arr = np.array([1, 2, 3, 4, 5])               |
    |  arr.shape β†’ (5,)                               |
    |  arr[0] β†’ 1                                     |
    |  arr + 1 β†’ [2, 3, 4, 5, 6]                     |
    +-------------------------------------------------+
    

Mini summary: NumPy arrays are fast, multi-dimensional containers for data. They are created using np.array() and other functions.


πŸ“˜ Lesson 4: Basic Array Operations with NumPy

Definition: NumPy allows you to perform mathematical operations on entire arrays at once, without loops.

Why it is important: This makes NumPy much faster and more concise than using regular Python lists.

Simple explanation: It is like being able to add 5 to every number in a list in one go, instead of using a loop.

Examples:

    arr = np.array([1, 2, 3, 4, 5])

    # Addition
    arr + 10  # [11, 12, 13, 14, 15]

    # Multiplication
    arr * 2   # [2, 4, 6, 8, 10]

    # Square
    arr ** 2  # [1, 4, 9, 16, 25]

    # Sum
    np.sum(arr)  # 15

    # Mean
    np.mean(arr)  # 3.0

    # Max and min
    np.max(arr)   # 5
    np.min(arr)   # 1
    

Real-life example: A financial analyst uses NumPy to calculate daily returns on a portfolio.

School example: You calculate the average of your test scores using np.mean().

Home example: You calculate total calories from a list of foods.

Nigerian example: A trader calculates total sales from daily sales figures using NumPy.

Illustration:

    ARRAY OPERATIONS
    +-------------------------------------------------+
    |  arr = np.array([1, 2, 3, 4, 5])               |
    |  arr + 1  β†’ [2, 3, 4, 5, 6]                   |
    |  arr * 2  β†’ [2, 4, 6, 8, 10]                  |
    |  np.mean(arr) β†’ 3.0                            |
    +-------------------------------------------------+
    

Mini summary: NumPy arrays support fast element-wise operations and aggregate functions like sum, mean, max, and min.


πŸ“˜ Lesson 5: Introduction to Pandas Series

Definition: A Pandas Series is a one-dimensional labeled array that can hold any data type. It is like a column in a spreadsheet.

Why it is important: Series are the building blocks of DataFrames. They allow you to work with labeled data, which makes analysis easier.

Simple explanation: Imagine you have a list of names and another list of ages. A Series can combine them with labels so you can refer to each item by name.

How to create a Series:

    import pandas as pd

    # From a list
    s = pd.Series([10, 20, 30, 40])

    # With custom index (labels)
    s = pd.Series([10, 20, 30, 40], index=['a', 'b', 'c', 'd'])

    # From a dictionary
    s = pd.Series({'a': 10, 'b': 20, 'c': 30})

    print(s['a'])  # 10
    

Real-life example: A Series could represent the daily temperatures for a week, with days as labels.

School example: A Series of student names and their grades.

Home example: A Series of family members' ages.

Nigerian example: A Series of product prices in a market, with product names as labels.

Illustration:

    PANDAS SERIES
    +-------------------------------------------------+
    |  s = pd.Series([10, 20, 30], index=['a','b','c']) |
    |  a    10                                         |
    |  b    20                                         |
    |  c    30                                         |
    |  dtype: int64                                    |
    +-------------------------------------------------+
    

Mini summary: A Pandas Series is a one-dimensional labeled array, useful for storing and working with data with labels.


πŸ“˜ Lesson 6: Introduction to Pandas DataFrames

Definition: A DataFrame is a two-dimensional labeled data structure with columns of potentially different types. It is like a spreadsheet or a SQL table.

Why it is important: DataFrames are the most common way to work with structured data in Python. They make data manipulation and analysis easy and intuitive.

Simple explanation: Think of a DataFrame as a well-organized table with rows and columns. Each column is a Series, and all columns share the same index (rows).

How to create a DataFrame:

    import pandas as pd

    # From a dictionary of lists
    data = {
        'Name': ['Ada', 'Chidi', 'Zainab'],
        'Age': [12, 14, 13],
        'City': ['Lagos', 'Abuja', 'Kano']
    }
    df = pd.DataFrame(data)

    print(df)
    #    Name  Age   City
    # 0   Ada   12  Lagos
    # 1 Chidi   14  Abuja
    # 2 Zainab  13   Kano
    

Real-life example: A company stores employee data in a DataFrame.

School example: Your teacher keeps student records in a spreadsheet, which is like a DataFrame.

Home example: You keep a budget in a table with columns for Date, Category, Amount.

Nigerian example: A bank stores customer information in a DataFrame.

Illustration:

    DATAFRAME STRUCTURE
    +-------------------------------------------------+
    |  Name     Age   City                            |
    |  Ada      12    Lagos                           |
    |  Chidi    14    Abuja                           |
    |  Zainab   13    Kano                            |
    +-------------------------------------------------+
    

Mini summary: A DataFrame is a two-dimensional labeled data structure, like a spreadsheet. It is the primary data structure in Pandas.


πŸ“˜ Lesson 7: Loading Data from CSV Files

Definition: CSV (Comma-Separated Values) is a common file format for storing tabular data. Pandas can easily read CSV files into DataFrames.

Why it is important: Most data you will work with comes from CSV files β€” from spreadsheets, databases, or web downloads.

Simple explanation: Think of a CSV file as a digital table. Pandas can read that table and put it into a DataFrame so you can analyse it.

How to read a CSV:

    df = pd.read_csv('data.csv')

    # You can also specify options
    df = pd.read_csv('data.csv', header=0, delimiter=',')
    

Real-life example: A data analyst downloads sales data as a CSV and loads it into Pandas.

School example: Your teacher saves class grades in a CSV file and reads it into Python.

Home example: You export your bank transactions as a CSV and analyse them in Pandas.

Nigerian example: A market researcher loads survey data from a CSV file into Pandas.

Illustration:

    CSV TO DATAFRAME
    +-------------------------------------------------+
    |  CSV file:                                     |
    |  Name,Age,City                                  |
    |  Ada,12,Lagos                                   |
    |  Chidi,14,Abuja                                 |
    +-------------------------------------------------+
    |  df = pd.read_csv('file.csv')                   |
    +-------------------------------------------------+
    

Mini summary: Use pd.read_csv() to load data from CSV files into a DataFrame for analysis.


πŸ“˜ Lesson 8: Exploring Data with Pandas

Definition: Exploring data means getting a first look at your DataFrame to understand its structure and content.

Why it is important: Before you analyse, you need to know what you are working with. Exploration helps you spot issues like missing values or unexpected data types.

Simple explanation: Imagine you have a new puzzle box. You look at the picture on the box, the number of pieces, and the shapes. That is exploring your data.

Common exploration methods:

    # View first 5 rows
    df.head()

    # View last 5 rows
    df.tail()

    # Get basic info (column types, non-null count)
    df.info()

    # Statistical summary
    df.describe()

    # Shape (rows, columns)
    df.shape

    # Column names
    df.columns

    # Data types
    df.dtypes
    

Real-life example: A business analyst checks the first few rows of sales data to see what columns exist.

School example: Your teacher previews a class list before taking attendance.

Home example: You look at your budget spreadsheet to see the categories you have.

Nigerian example: A data analyst uses describe() to understand the distribution of product prices.

Illustration:

    EXPLORING DATA
    +-------------------------------------------------+
    |  df.head()  β†’ first 5 rows                      |
    |  df.info()  β†’ column types and null counts      |
    |  df.describe() β†’ stats for numeric columns      |
    +-------------------------------------------------+
    

Mini summary: Use head(), info(), describe(), and other methods to explore your DataFrame.


πŸ“˜ Lesson 9: Selecting and Filtering Data

Definition: Selecting means choosing specific rows or columns. Filtering means choosing rows that meet a condition.

Why it is important: You often need to work with only a part of your dataβ€”for example, only sales in a particular region or only students with a certain grade.

Simple explanation: It is like picking apples from a basket β€” you only take the ones that are ripe (filtering) or you take only the ones from the top layer (selecting).

Examples:

    # Select a single column
    df['Name']

    # Select multiple columns
    df[['Name', 'Age']]

    # Select rows by index position (0-4)
    df.iloc[0:5]

    # Select rows by label
    df.loc[0:5]

    # Filter rows where Age > 12
    df[df['Age'] > 12]

    # Filter with multiple conditions
    df[(df['Age'] > 12) & (df['City'] == 'Lagos')]
    

Real-life example: A store manager filters sales data to see only transactions from the Lagos branch.

School example: A teacher selects only the students who scored above 70%.

Home example: You filter your expenses to show only those for food.

Nigerian example: A market researcher filters survey responses by age group.

Illustration:

    FILTERING DATA
    +-------------------------------------------------+
    |  df[df['Age'] > 12]                             |
    |  Returns rows where Age is greater than 12      |
    +-------------------------------------------------+
    

Mini summary: Use df[column] or df[['col1','col2']] to select columns. Use boolean conditions to filter rows.


πŸ“˜ Lesson 10: Handling Missing Data

Definition: Missing data are values that are not present in your dataset. They are often represented as NaN (Not a Number).

Why it is important: Missing data can cause problems in analysis. You need to decide how to handle them β€” either remove rows with missing values or fill them with something else.

Simple explanation: Imagine you have a survey where some people did not answer a question. You cannot just ignore them; you have to decide what to do with those missing answers.

How to handle:

    # Check for missing values
    df.isnull().sum()

    # Drop rows with any missing values
    df.dropna()

    # Drop rows where a specific column has missing values
    df.dropna(subset=['Age'])

    # Fill missing values with a specific value
    df.fillna(0)

    # Fill missing values with the mean of the column
    df['Age'].fillna(df['Age'].mean())
    

Real-life example: A data analyst drops rows with missing customer information before building a model.

School example: Your teacher ignores blank answers on a test when calculating the average.

Home example: You fill in missing grocery prices with the average price from other stores.

Nigerian example: A market researcher replaces missing product ratings with the average rating.

Illustration:

    MISSING DATA
    +-------------------------------------------------+
    |  Before:                                        |
    |  Name    Age   City                             |
    |  Ada     12    Lagos                            |
    |  Chidi   NaN   Abuja                            |
    |  Zainab  13    NaN                              |
    +-------------------------------------------------+
    |  dropna() β†’ removes rows 1 and 2               |
    |  fillna(0) β†’ fills NaN with 0                  |
    +-------------------------------------------------+
    

Mini summary: Use dropna() to remove missing values or fillna() to fill them with a value.


πŸ“˜ Lesson 11: Grouping and Aggregating Data

Definition: Grouping means splitting data into groups based on some criteria, and then applying an aggregation function (like sum, mean, count) to each group.

Why it is important: Grouping is essential for summarizing data. For example, you might want to know the average sales per city or the total spending per category.

Simple explanation: Imagine you have a list of students and their grades. You want to find the average grade for each class. Grouping lets you separate students by class and then calculate the average for each group.

How to use groupby:

    # Group by City and calculate mean age
    df.groupby('City')['Age'].mean()

    # Group by City and get multiple aggregates
    df.groupby('City').agg({'Age': ['mean', 'count']})

    # Group by multiple columns
    df.groupby(['City', 'Gender'])['Age'].mean()
    

Real-life example: A store groups sales by product category to see which category brings in the most revenue.

School example: A teacher groups students by class to calculate the average score per class.

Home example: You group your expenses by category (food, transport, entertainment) to see where you spend most.

Nigerian example: A market analyst groups product sales by region to see which region has the highest sales.

Illustration:

    GROUPBY EXAMPLE
    +-------------------------------------------------+
    |  df.groupby('City')['Age'].mean()               |
    |  City                                           |
    |  Abuja   14.0                                   |
    |  Kano    13.0                                   |
    |  Lagos   12.0                                   |
    +-------------------------------------------------+
    

Mini summary: Use groupby() to split data into groups and agg() or aggregation functions to summarize each group.


πŸ“˜ Lesson 12: Applying Functions to Data

Definition: Sometimes you need to apply a custom function to each element, row, or column. Pandas provides apply() and map() for this.

Why it is important: Not all transformations can be done with built-in methods. You may need to create your own logic.

Simple explanation: Imagine you have a list of temperatures in Celsius, and you want to convert them to Fahrenheit. You need to apply a conversion function to each element.

Examples:

    # Apply a function to a column
    def double(x):
        return x * 2

    df['Age_doubled'] = df['Age'].apply(double)

    # Using lambda
    df['Age_doubled'] = df['Age'].apply(lambda x: x * 2)

    # Apply to entire row (axis=1)
    df['Total'] = df[['col1', 'col2']].apply(lambda row: row[0] + row[1], axis=1)

    # Map values in a column
    df['City_code'] = df['City'].map({'Lagos': 'LA', 'Abuja': 'AB', 'Kano': 'KN'})
    

Real-life example: A data scientist applies a function to normalize data (scale it to a range).

School example: You apply a function to convert percentage grades to letter grades.

Home example: You apply a function to calculate the total cost of items including tax.

Nigerian example: A market analyst applies a function to convert prices from naira to dollars using the current exchange rate.

Illustration:

    APPLY FUNCTION
    +-------------------------------------------------+
    |  df['Age'].apply(lambda x: x * 2)               |
    |  Applies the doubling function to each age      |
    +-------------------------------------------------+
    

Mini summary: Use apply() and map() to apply custom functions to your data.


πŸ“˜ Lesson 13: Saving Data and Basic Visualization

Definition: After analysis, you often want to save the results to a file. You can also create basic plots to visualize your data.

Why it is important: Saving allows you to share your results. Visualization helps you understand patterns and communicate insights.

How to save:

    # Save to CSV
    df.to_csv('output.csv', index=False)

    # Save to Excel
    df.to_excel('output.xlsx', index=False)
    

Basic plotting with Pandas and Matplotlib:

    import matplotlib.pyplot as plt

    # Line plot
    df['Age'].plot()
    plt.show()

    # Bar chart
    df['City'].value_counts().plot(kind='bar')
    plt.show()

    # Histogram
    df['Age'].plot(kind='hist')
    plt.show()

    # Scatter plot
    df.plot.scatter(x='Age', y='Score')
    plt.show()
    

Real-life example: A business analyst creates a bar chart of sales by product category.

School example: You create a histogram of test scores to see the distribution.

Home example: You make a pie chart of your monthly expenses.

Nigerian example: A market researcher plots a bar chart of product popularity across different regions.

Illustration:

    VISUALIZATION
    +-------------------------------------------------+
    |  df['Age'].plot(kind='hist')                    |
    |  Displays a histogram of ages                   |
    +-------------------------------------------------+
    

Mini summary: Save DataFrames to CSV or Excel. Use .plot() with Matplotlib for basic visualizations.


πŸ“˜ Lesson 14: Putting It All Together – A Complete Analysis

Now we will perform a complete data analysis using Pandas and NumPy on a sample dataset.

Scenario: We have a CSV file containing student grades and demographic information. We will load, explore, clean, analyse, and visualize the data.

Code example:

    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt

    # Load data
    df = pd.read_csv('students.csv')

    # Explore
    print(df.head())
    print(df.info())
    print(df.describe())

    # Handle missing values
    df = df.dropna(subset=['Grade'])

    # Create a new column: Passing (Grade >= 60)
    df['Pass'] = df['Grade'] >= 60

    # Group by gender and calculate average grade
    avg_grade = df.groupby('Gender')['Grade'].mean()
    print(avg_grade)

    # Group by gender and count passes
    pass_count = df.groupby('Gender')['Pass'].sum()
    print(pass_count)

    # Visualization
    df.groupby('Gender')['Grade'].plot(kind='bar')
    plt.title('Average Grade by Gender')
    plt.show()

    # Save results
    df.to_csv('cleaned_students.csv', index=False)
    

What we used:

  • Pandas for loading and manipulation
  • NumPy for calculations (implicitly)
  • Matplotlib for plotting
  • Groupby and aggregation
  • Boolean columns
  • Data cleaning

Illustration:

    COMPLETE ANALYSIS FLOW
    +-------------------------------------------------+
    |  Load CSV β†’ Explore β†’ Clean β†’ Transform β†’ Analyse β†’ Visualize β†’ Save |
    +-------------------------------------------------+
    

Mini summary: The complete analysis combines all the steps: loading, exploring, cleaning, transforming, grouping, and visualizing data to extract insights.


πŸ“– Key Vocabulary

Word Simple Definition
NumPy A library for fast numerical operations on arrays.
Pandas A library for data analysis with DataFrames and Series.
Array A grid of values, all of the same type, in NumPy.
Series A one-dimensional labeled array in Pandas.
DataFrame A two-dimensional labeled data structure, like a spreadsheet.
CSV Comma-Separated Values, a common file format for tables.
Missing Data Values that are not present, often represented as NaN.
Groupby A method to split data into groups and apply functions.
Aggregation Summarizing data with functions like sum, mean, count.
Visualization Creating charts and graphs to represent data.

⭐ Important Concepts

  • NumPy arrays are fast and efficient for mathematical operations. They are the backbone of many data science libraries.
  • Pandas DataFrames are the most common way to work with structured data in Python. They offer powerful tools for filtering, grouping, and cleaning data.
  • Data cleaning is an essential step. Always check for missing values and decide how to handle them.
  • Grouping and aggregation allow you to summarize data and find patterns.
  • Visualization helps you communicate your findings effectively.
  • Combining NumPy, Pandas, and Matplotlib gives you a powerful toolkit for data analysis.

πŸ”§ Step-by-Step Explanations

πŸ”Ή How to Load a CSV File with Pandas

  1. Import pandas: import pandas as pd.
  2. Use pd.read_csv('filename.csv').
  3. Specify options like header, delimiter, etc., if needed.
  4. Assign to a variable: df = pd.read_csv(...).

πŸ”Ή How to Filter Rows Based on a Condition

  1. Write a condition: df['column'] > value.
  2. Use it inside brackets: df[df['column'] > value].
  3. Combine conditions with & (and) or | (or).

πŸ”Ή How to Group and Aggregate Data

  1. Choose a column to group by: df.groupby('col').
  2. Select a column to aggregate: df.groupby('col')['value'].
  3. Apply an aggregation function: .mean(), .sum(), .count(), etc.
  4. Use .agg() for multiple aggregations.

🌍 Real-life Examples

  • Sales analysis: A retail company uses Pandas to analyse daily sales, find best-selling products, and forecast demand.
  • Financial analysis: A bank uses NumPy to calculate risk metrics and Pandas to manage customer data.
  • Healthcare: A hospital analyses patient data to identify trends in diseases and treatment outcomes.
  • Education: A school uses Pandas to track student performance and identify at-risk students.
  • Marketing: A company analyses campaign data to see which ads are most effective.

πŸ‡³πŸ‡¬ Nigerian Examples

  • Market analysis: A trader uses Pandas to compare prices of tomatoes across different Lagos markets.
  • Education: A school in Enugu uses Pandas to analyse WAEC results and improve teaching strategies.
  • Agriculture: A farmer uses NumPy to analyse rainfall and yield data to optimize planting schedules.
  • Finance: A fintech startup in Abuja uses Pandas to detect fraudulent transactions.
  • Transport: A logistics company uses Pandas to analyse delivery times and optimize routes.

🎈 Fun Examples Children Can Relate To

  • Game scores: Analyse scores from your favourite video game to see which level is hardest.
  • Candy collection: Use Pandas to count how many candies of each colour you have.
  • Reading log: Track the number of pages you read each day and find the average.
  • Pocket money: Analyse your spending habits to see where you spend most.
  • Weather: Record temperatures for a week and plot them to see the trend.

🏠 Everyday Examples

  • Budgeting: Use Pandas to track monthly income and expenses.
  • Grocery list: Analyse which items you buy most often.
  • Exercise log: Track steps or calories and visualize progress.
  • Study planner: Record study hours per subject and see which subject gets most time.
  • Reading: Keep a log of books read and analyse reading patterns.

πŸ‘©β€πŸ« Teacher Notes

  • Use real datasets: Provide students with interesting datasets (e.g., weather data, sports statistics) to make learning engaging.
  • Hands-on practice: Have students load and explore data on their own computers.
  • Encourage exploration: Let students ask their own questions and try to answer them with Pandas.
  • Visualization: Show how plotting can reveal patterns that numbers alone cannot.
  • Discuss data ethics: Talk about privacy and responsible data handling.

πŸ‘ͺ Parent Tips

  • Encourage curiosity: Help your child find data they are interested in (e.g., sports, weather, pocket money).
  • Explore together: Look at charts and discuss what they show.
  • Provide access: Ensure your child can install Python and the necessary libraries.
  • Celebrate insights: When your child discovers something interesting in data, celebrate the find.

πŸ€” Interesting Facts

  • NumPy is written in C and Python, which makes it very fast β€” up to 50 times faster than pure Python loops.
  • The name "Pandas" comes from "Panel Data," which is a term from econometrics.
  • Pandas was created by Wes McKinney in 2008 while he was working at AQR Capital Management.
  • NumPy's array operations are so efficient that many other libraries (like Pandas, SciPy, and Scikit-learn) are built on top of it.
  • Pandas is one of the most downloaded Python libraries, with over 100 million downloads per month.

πŸ’‘ Did You Know?

  • Did you know? You can read Excel files directly into Pandas using pd.read_excel().
  • Did you know? NumPy arrays can be multi-dimensional (e.g., 2D matrices).
  • Did you know? Pandas can handle time series data easily with date-time indexing.
  • Did you know? You can use df.query() to filter data using a string expression.
  • Did you know? Pandas can merge and join DataFrames like SQL tables.

🧠 Remember This

  • NumPy provides fast arrays for numerical operations.
  • Pandas provides DataFrames for structured data analysis.
  • Use pd.read_csv() to load data from CSV files.
  • Explore data with head(), info(), and describe().
  • Filter data with boolean conditions.
  • Handle missing values with dropna() and fillna().
  • Group and aggregate with groupby().
  • Apply custom functions with apply().
  • Visualize data with Matplotlib.
  • Practice is the key to mastering data analysis.

⚠️ Common Mistakes

Mistake How to Avoid It
Forgetting to install pandas or numpy Always pip install pandas numpy matplotlib.
Using df['column'] when column doesn't exist Check column names with df.columns.
Not handling missing values before analysis Always check for nulls with df.isnull().sum().
Applying functions without axis parameter Remember axis=1 for row-wise operations.
Modifying a slice of a DataFrame without using .copy() Use df_copy = df.copy() to avoid warnings.
Forgetting to import matplotlib Always import import matplotlib.pyplot as plt.
Using value_counts() on non-categorical data It works, but use it on categorical columns for best results.

βœ… Best Practices

  • Always explore your data before analysing. Use head(), info(), and describe().
  • Handle missing data appropriately β€” know when to drop and when to impute.
  • Use meaningful variable names for DataFrames and columns.
  • Comment your code to explain what you are doing, especially for complex transformations.
  • Save intermediate results to avoid recomputation.
  • Visualize your results to make insights clear.
  • Document your analysis with a summary of your findings.

πŸ–ΌοΈ Diagrams and Illustrations

DataFrame Structure

    DATAFRAME STRUCTURE
    +-------------------------------------------------+
    |  Index  |  Name   |  Age   |  City              |
    |  0      |  Ada    |  12    |  Lagos             |
    |  1      |  Chidi  |  14    |  Abuja             |
    |  2      |  Zainab |  13    |  Kano              |
    +-------------------------------------------------+
    

Data Analysis Pipeline

    DATA ANALYSIS PIPELINE
    +-------------------------------------------------+
    |  Raw Data (CSV)                                 |
    |         ↓                                        |
    |  Load with pd.read_csv()                         |
    |         ↓                                        |
    |  Explore (head, info, describe)                 |
    |         ↓                                        |
    |  Clean (dropna, fillna)                         |
    |         ↓                                        |
    |  Transform (apply, map)                         |
    |         ↓                                        |
    |  Group and Aggregate (groupby)                  |
    |         ↓                                        |
    |  Visualize (plot)                               |
    |         ↓                                        |
    |  Save (to_csv)                                  |
    +-------------------------------------------------+
    

Groupby Operation

    GROUPBY OPERATION
    +-------------------------------------------------+
    |  df.groupby('City')['Age'].mean()               |
    |  City                                           |
    |  Lagos    12.0                                  |
    |  Abuja    14.0                                  |
    |  Kano     13.0                                  |
    +-------------------------------------------------+
    

Missing Data Handling

    MISSING DATA HANDLING
    +-------------------------------------------------+
    |  Before:                                        |
    |  Name    Age   City                             |
    |  Ada     12    Lagos                            |
    |  Chidi   NaN   Abuja                            |
    |  Zainab  13    NaN                              |
    +-------------------------------------------------+
    |  dropna() β†’ removes rows 1 and 2               |
    |  fillna(0) β†’ fills NaN with 0                  |
    +-------------------------------------------------+
    

πŸ“Š Comparison Tables

Comparison: NumPy Array vs. Python List

Feature NumPy Array Python List
Memory Less (fixed type) More (arbitrary types)
Speed Fast (vectorized) Slower (loops)
Element-wise operations Built-in Need loops
Data types All elements same type Any type
Use case Numerical computing General-purpose

Comparison: Series vs. DataFrame

Feature Series DataFrame
Dimensions 1D 2D
Index Yes Yes
Columns Single Multiple
Use case Column of data Full table

Lesson 1 Summary: NumPy provides fast numerical arrays; Pandas provides DataFrames for analysis.

Lesson 2 Summary: Install NumPy, Pandas, and Matplotlib with pip.

Lesson 3 Summary: NumPy arrays are fast, multi-dimensional containers.

Lesson 4 Summary: NumPy supports fast element-wise operations and aggregations.

Lesson 5 Summary: Pandas Series are one-dimensional labeled arrays.

Lesson 6 Summary: DataFrames are two-dimensional labeled structures like spreadsheets.

Lesson 7 Summary: Use pd.read_csv() to load data from CSV files.

Lesson 8 Summary: Explore data with head(), info(), describe().

Lesson 9 Summary: Select and filter data using column names and boolean conditions.

Lesson 10 Summary: Handle missing data with dropna() and fillna().

Lesson 11 Summary: Group and aggregate data with groupby().

Lesson 12 Summary: Apply custom functions with apply() and map().

Lesson 13 Summary: Save data to CSV/Excel and create basic plots.

Lesson 14 Summary: The complete analysis flow combines all steps.


πŸ“ End-of-Module Summary

Congratulations! You have completed Module Three πŸŽ‰. You now have a solid foundation in data analysis with Python using NumPy and Pandas.

You learned how to use NumPy for fast numerical operations and Pandas for data manipulation and analysis. You can load data from CSV files, explore and clean it, filter and group it, and even create basic visualizations. You have built a complete data analysis pipeline.

These skills are in high demand across many industries β€” from business and finance to healthcare and technology. With this knowledge, you can turn raw data into actionable insights.

In the next module, you will dive deeper into data visualization with Matplotlib and Seaborn, learning how to create professional and informative plots.

Keep practising by finding datasets that interest you and analysing them. The more you practice, the more confident you will become. You are now a data analyst! πŸ“Š


❓ Frequently Asked Questions

  1. Q: Do I need to know NumPy before learning Pandas?
    A: Not necessarily, but understanding NumPy helps because Pandas is built on top of it.
  2. Q: Can I use Pandas to analyse data from Excel?
    A: Yes, you can use pd.read_excel() to read Excel files.
  3. Q: What is the difference between loc and iloc?
    A: loc uses labels (index names), while iloc uses integer positions.
  4. Q: How do I filter a DataFrame with multiple conditions?
    A: Use & for AND and | for OR, with parentheses around each condition.
  5. Q: What is the best way to handle missing data?
    A: It depends on the context. Sometimes you drop the rows; other times you fill with a value (mean, median, etc.).
  6. Q: Can I plot directly from a Pandas DataFrame?
    A: Yes, you can use df.plot() which is built on Matplotlib.
  7. Q: What is the difference between apply() and map()?
    A: apply() works on rows or columns; map() works element-wise on a Series.
  8. Q: How do I save a DataFrame to an Excel file?
    A: Use df.to_excel('file.xlsx', index=False).
  9. Q: Is Pandas suitable for large datasets?
    A: Yes, but for very large datasets (hundreds of GB), you might need other tools like Dask or Vaex.
  10. Q: What is the next step after learning Pandas?
    A: You can learn more advanced visualization with Seaborn, or dive into machine learning with Scikit-learn.

πŸ“ Review Questions

  1. What are NumPy and Pandas and what are they used for?
  2. How do you install NumPy, Pandas, and Matplotlib?
  3. What is a NumPy array and how is it different from a Python list?
  4. How do you create a NumPy array of zeros?
  5. What is a Pandas Series?
  6. What is a Pandas DataFrame and how do you create one?
  7. How do you load a CSV file into a DataFrame?
  8. What methods would you use to explore a DataFrame?
  9. How do you select a single column from a DataFrame?
  10. How do you filter rows based on a condition?
  11. How do you handle missing values in a DataFrame?
  12. What is the purpose of groupby()?
  13. How do you apply a custom function to a column?
  14. How do you save a DataFrame to a CSV file?
  15. What is the complete analysis flow an example of?

✏️ Fill-in-the-Blank Exercises

  1. __________ is a library for fast numerical computing in Python.
  2. __________ is a library for data analysis with DataFrames.
  3. A __________ is a one-dimensional labeled array in Pandas.
  4. A __________ is a two-dimensional labeled data structure.
  5. To load a CSV file, use the function __________.
  6. To view the first few rows of a DataFrame, use __________.
  7. To get summary statistics, use __________.
  8. Missing values are often represented as __________.
  9. To remove rows with missing values, use __________.
  10. To group data, use the method __________.
  11. To apply a function to a column, use __________.
  12. To save a DataFrame to a CSV file, use __________.
  13. The __________ library is used for visualization.
  14. df['Age'] > 12 returns a __________ Series.
  15. The complete analysis flow includes loading, cleaning, analysing, and __________.

βœ… True or False Exercises

  1. NumPy arrays can hold different data types in the same array. (True / False)
  2. Pandas DataFrames are immutable. (True / False)
  3. df.head() shows the last 5 rows. (True / False)
  4. df.describe() only works on numeric columns. (True / False)
  5. Missing values are represented as None in Pandas. (True / False)
  6. dropna() removes rows with any missing value. (True / False)
  7. groupby() is used to filter data. (True / False)
  8. apply() can be used to apply a function to a column. (True / False)
  9. to_csv() saves a DataFrame to an Excel file. (True / False)
  10. Matplotlib is required for plotting with Pandas. (True / False)
  11. df['column'] returns a Series. (True / False)
  12. You cannot combine multiple conditions in a filter. (True / False)
  13. fillna() replaces missing values with a specified value. (True / False)
  14. NumPy arrays are slower than Python lists. (True / False)
  15. Data analysis always follows the same flow: load, explore, clean, analyse, visualize. (True / False)

πŸ”˜ Multiple Choice Questions

  1. Which library provides DataFrames?
    a) NumPy
    b) Pandas
    c) Matplotlib
    d) SciPy
    Answer: b)
  2. Which function loads a CSV file into a DataFrame?
    a) pd.load_csv()
    b) pd.read_csv()
    c) pd.read_file()
    d) pd.import_csv()
    Answer: b)
  3. What does df.head() do?
    a) Returns the last 5 rows
    b) Returns the first 5 rows
    c) Returns a summary of the DataFrame
    d) Returns the column names
    Answer: b)
  4. Which method removes rows with missing values?
    a) dropna()
    b) fillna()
    c) drop_na()
    d) remove_na()
    Answer: a)
  5. Which method fills missing values?
    a) dropna()
    b) fillna()
    c) replace_na()
    d) na_fill()
    Answer: b)
  6. Which method groups data in Pandas?
    a) group()
    b) groupby()
    c) group_by()
    d) by_group()
    Answer: b)
  7. How do you select a column named 'Age' in a DataFrame?
    a) df['Age']
    b) df.Age
    c) Both a and b
    d) df(column='Age')
    Answer: c)
  8. What is the purpose of apply()?
    a) To apply a function to each element in a Series
    b) To filter data
    c) To load data
    d) To save data
    Answer: a)
  9. Which library is used for plotting in Pandas?
    a) NumPy
    b) Matplotlib
    c) SciPy
    d) Seaborn
    Answer: b)
  10. What is a NumPy array?
    a) A list of mixed types
    b) A multi-dimensional container of fixed-type elements
    c) A DataFrame
    d) A Series
    Answer: b)
  11. How do you get summary statistics of numeric columns?
    a) df.summary()
    b) df.describe()
    c) df.info()
    d) df.stats()
    Answer: b)
  12. Which method saves a DataFrame to a CSV file?
    a) df.to_csv()
    b) df.save_csv()
    c) df.write_csv()
    d) df.export_csv()
    Answer: a)
  13. What does df.info() display?
    a) Summary statistics
    b) Column names, data types, and non-null counts
    c) The first 5 rows
    d) The shape of the DataFrame
    Answer: b)
  14. What is the complete analysis flow an example of?
    a) A simple script
    b) A complete data analysis pipeline
    c) A web application
    d) A machine learning model
    Answer: b)
  15. Which method is used to create a NumPy array?
    a) np.array()
    b) np.create()
    c) np.ndarray()
    d) np.list()
    Answer: a)

πŸ”— Matching Exercises

Match the term on the left with its description on the right:

Term Description
1. NumPy A. One-dimensional labeled array
2. Pandas B. Two-dimensional labeled data structure
3. Series C. Fast numerical arrays
4. DataFrame D. Data analysis library
5. groupby E. Splits data into groups
6. dropna F. Removes missing values

Answers: 1-C, 2-D, 3-A, 4-B, 5-E, 6-F


πŸ“ Short Answer Questions

  1. Explain the difference between NumPy arrays and Python lists.
  2. What is a Pandas DataFrame and how is it useful?
  3. Describe the steps to load and explore a CSV file using Pandas.
  4. How do you filter a DataFrame to only include rows where a column is greater than a certain value?
  5. What are the common ways to handle missing data in Pandas?
  6. Why is grouping and aggregation important in data analysis?
  7. How do you apply a custom function to a column in a DataFrame?
  8. What is the purpose of the describe() method?
  9. How do you save a DataFrame to a CSV file?
  10. What is the complete analysis flow an example of?

🎭 Scenario-based Exercises

Scenario 1:

Ada has a CSV file with sales data: Date, Product, Quantity, Price. She wants to find the total sales per product and the average price per product. Write the Pandas code to do this.

Scenario 2:

Chidi has a dataset with missing values in the Age column. He wants to fill the missing ages with the median age. Write the code.

Scenario 3:

Zainab wants to create a bar chart of the top 5 products by total sales. Write the Pandas and Matplotlib code.


πŸ‘₯ Group Activity

Activity Title: Analyse a Real Dataset

Instructions:

  1. Divide the class into groups of 3–4 students.
  2. Each group downloads a public dataset (e.g., from Kaggle or data.gov.ng) or uses a provided dataset.
  3. Each group performs a complete analysis:
    • Load the data.
    • Explore and clean it.
    • Answer at least 3 questions (e.g., "What is the average?", "Which category has highest?", etc.).
    • Create at least 2 visualizations.
    • Present findings to the class.

πŸ§‘β€πŸŽ“ Individual Activity

Activity Title: Analyse Your Personal Data

Instructions:

  1. Collect data from your own life (e.g., daily steps, study hours, expenses, grades).
  2. Create a CSV file with your data.
  3. Write a Python script using Pandas to:
    • Load the data.
    • Explore it.
    • Clean it if needed.
    • Calculate summaries (mean, total, etc.).
    • Create at least one plot.
    • Save the cleaned data.
  4. Submit your script and a brief report of your findings.

πŸ’¬ Classroom Discussion Questions

  1. Why is data analysis important in today's world?
  2. What are some ethical considerations when analysing data?
  3. How can data analysis help businesses make better decisions?
  4. What are the challenges of working with large datasets?
  5. How can visualization make data insights more accessible?
  6. What is the most interesting thing you learned about data analysis?
  7. What kind of data would you like to analyse in the future?

πŸ› οΈ Mini Project

Project Title: Build a Data Analysis Dashboard

Description:

Create a Python script that loads a dataset, performs analysis, and generates a dashboard of charts and statistics. The dashboard should:

  • Load data from a CSV file.
  • Display summary statistics.
  • Show at least 3 different charts (e.g., bar chart, histogram, pie chart).
  • Include a written summary of insights.
  • Save the results to a CSV file.

Use Pandas, NumPy, and Matplotlib. This project will test your ability to combine all the skills from this module.


πŸ’» Practical Assignment

Assignment Title: Analyse Student Performance Data

Instructions:

  1. Download the student performance dataset (or use a provided one). It should include columns like: Student_ID, Gender, Class, Subject, Score.
  2. Write a Python script that:
    • Loads the data.
    • Calculates the average score per subject.
    • Calculates the average score per gender.
    • Identifies the top 5 students with highest average scores.
    • Creates a bar chart of average scores by subject.
    • Saves the results to a CSV file.
  3. Submit your script and the output CSV file.

πŸ† Challenge Exercise

Challenge Title: Analyse and Predict Sales

You have a dataset of daily sales for a store over one year. The dataset includes: Date, Product_ID, Sales, Discount. Your task is to:

  • Load and explore the data.
  • Handle missing values and outliers.
  • Find the total sales per month and per product.
  • Identify the product with the highest average daily sales.
  • Analyse the relationship between discount and sales (hint: use correlation or groupby).
  • Create visualizations to support your findings.
  • Write a summary report of your analysis.

This challenge will test your ability to handle a real-world dataset and extract meaningful insights. Good luck!


πŸ“ Quiz Answers

Fill-in-the-Blank Answers:

  1. NumPy
  2. Pandas
  3. Series
  4. DataFrame
  5. pd.read_csv()
  6. df.head()
  7. df.describe()
  8. NaN
  9. dropna()
  10. groupby()
  11. apply()
  12. df.to_csv()
  13. Matplotlib
  14. boolean
  15. visualize

True or False Answers:

  1. False
  2. False
  3. False
  4. True
  5. False
  6. True
  7. False
  8. True
  9. False
  10. True
  11. True
  12. False
  13. True
  14. False
  15. True

Multiple Choice Answers:

  1. b
  2. b
  3. b
  4. a
  5. b
  6. b
  7. c
  8. a
  9. b
  10. b
  11. b
  12. a
  13. b
  14. b
  15. a

πŸ”‘ Key Takeaways

  • NumPy provides fast, efficient numerical arrays.
  • Pandas provides powerful DataFrames for data manipulation and analysis.
  • Data cleaning (handling missing values, filtering) is a critical first step.
  • Grouping and aggregation help summarize data and find patterns.
  • Visualization helps communicate insights effectively.
  • The complete analysis flow is: load, explore, clean, transform, analyse, visualize, and save.
  • Practice with real datasets is the best way to master data analysis.

πŸš€ Preparation for the Next Module

Excellent work completing Module Three! πŸŽ‰ You have gained valuable skills in data analysis with Pandas and NumPy. In the next module, you will learn:

  • Advanced Data Visualization with Matplotlib and Seaborn β€” creating professional, publication-quality plots.
  • Customizing Plots β€” adding titles, labels, legends, and annotations.
  • Statistical Visualizations β€” box plots, violin plots, heatmaps, and more.
  • Time Series Analysis β€” plotting data over time.
  • Interactive Visualizations with Plotly.

To prepare, review the plotting basics from this module and explore some datasets you would like to visualize. The more you practice, the better your visualizations will become.

Keep coding, keep exploring data, and never stop learning. See you in the next module! πŸπŸ“Š


πŸŽ‰ End of Module Three – Python Fundamentals Level Two πŸŽ‰

πŸ† Get Certified

πŸ”’

Earn this certificate

Every lesson is already free to read. Sign up, finish the lessons, pass the exam (₦2,000 or 20,000 coins), and get a verified certificate with your name on it.

πŸŽ“ Sign Up to Get Certified
πŸ› οΈ Practice Tools
Hands-on simulators & labs - subscription required.
β†’
🎯 Internship Tasks
Real-world tasks to build your portfolio - unlock them with a subscription.
β†’