Hiring Partners
Segilola Resources Operating LimitedTaviatech TechnologiesFCMBMTN NigeriaAdvans La Fayette Microfinance BankAboki AfricaFirst Bank of NigeriaOPay
โ† Introduction to Python for Data Analysis ยท Lesson 6 of 9

Module Five

๐Ÿ“– 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.
6
Module 5: Introduction to Python Data Analysis Libraries Course: Introduction to Python for Data Analysis | Beginner-friendly lesson for 13-year-olds In this module, you will learn about Python libraries and how they help data analysts work with information, perform calculations, and create charts. ```

Module 5: Introduction to Data Analysis Libraries

Welcome to Module 5! In the previous modules, you learned Python basics, variables, data types, lists, dictionaries, conditions, loops, and functions.

Now, you are ready to explore something exciting: Python libraries.

Python libraries provide ready-made instructions that help programmers perform different tasks without writing every instruction from the beginning.

5.1 What Are Python Libraries?

A Python library is a collection of ready-made code that helps programmers perform specific tasks.

Imagine you want to build a house. Instead of making every building material yourself, you can buy ready-made bricks, doors, windows, and roofing materials.

Python libraries work in a similar way. They provide tools that make programming easier and faster.

For example, instead of writing hundreds of instructions to calculate the average of thousands of numbers, you can use a Python library that already has tools for calculations.

Why Are Python Libraries Important?

  • They save time when writing programs.
  • They make difficult tasks easier.
  • They provide ready-made tools for calculations.
  • They help organise and analyse large amounts of information.
  • They make it easier to create charts and visual reports.

5.2 Introduction to NumPy

NumPy stands for Numerical Python. It is a Python library used mainly for working with numbers and performing mathematical calculations.

Imagine a teacher has examination scores for 1,000 students. Instead of calculating everything manually, NumPy can help process the numbers quickly.

What Can NumPy Do?

  • Perform mathematical calculations.
  • Work with large collections of numbers.
  • Calculate averages and totals.
  • Find the highest and lowest values.
  • Perform statistical calculations.

Installing NumPy

If you are using Google Colab, NumPy is usually already available. You can import it directly.

If you are using a local Python environment, you can install it with this command:

pip install numpy

Importing NumPy

Before using NumPy, you need to import it into your Python program.

import numpy as np

The letters np are a short name commonly used for NumPy. This makes it easier to write NumPy instructions.

Creating a NumPy Array

An array is a collection of values stored together. NumPy arrays are useful for performing calculations on groups of numbers.

import numpy as np

scores = np.array([70, 80, 90, 60, 85])

print(scores)

Output:

[70 80 90 60 85]

Calculating the Average with NumPy

NumPy can calculate the average of several numbers using the mean() function.

import numpy as np

scores = np.array([70, 80, 90, 60, 85])

average = np.mean(scores)

print(average)

Output:

77.0

The average examination score is 77.

Finding the Highest and Lowest Values

You can use NumPy to find the highest and lowest numbers in a collection.

import numpy as np

scores = np.array([70, 80, 90, 60, 85])

print(np.max(scores))
print(np.min(scores))

Output:

90
60

NumPy has identified 90 as the highest score and 60 as the lowest score.

5.3 Introduction to Pandas

Pandas is a popular Python library used to organise, clean, and analyse data.

Think about an Excel spreadsheet containing students' names, ages, classes, and examination scores. Pandas allows you to work with this type of information using Python.

Pandas is especially useful when working with information stored in rows and columns.

What Can Pandas Do?

  • Read information from Excel and CSV files.
  • Organise information into tables.
  • Select specific rows and columns.
  • Sort and filter information.
  • Identify missing information.
  • Remove duplicate records.
  • Calculate totals, averages, and other statistics.

Installing Pandas

If you are using Google Colab, Pandas is usually already installed.

For a local Python installation, use this command:

pip install pandas

Importing Pandas

To use Pandas, import it into your program.

import pandas as pd

The letters pd are the commonly used short name for Pandas.

Creating a Simple Pandas DataFrame

A DataFrame is a table-like structure with rows and columns. It is similar to a spreadsheet in Microsoft Excel.

Example:

import pandas as pd

data = {
    "Student": ["Ada", "Tunde", "Musa", "Grace"],
    "Score": [85, 70, 90, 65]
}

table = pd.DataFrame(data)

print(table)

Output:

  Student  Score
0     Ada     85
1   Tunde     70
2    Musa     90
3   Grace     65

Python has created a table containing students' names and examination scores.

Viewing a Column in Pandas

You can select one column from a DataFrame by using its column name.

print(table["Student"])

This displays the names of the students.

Calculating the Average Score with Pandas

average_score = table["Score"].mean()

print(average_score)

Output:

77.5

Pandas has calculated the average examination score of the four students.

5.4 Introduction to Matplotlib

Matplotlib is a Python library used to create charts and graphs.

Imagine a supermarket owner wants to understand how much money the business makes every day. Looking at a long list of numbers may be difficult.

A chart can make the information easier to understand.

Matplotlib helps turn numbers into visual information.

What Can Matplotlib Do?

  • Create bar charts.
  • Create line graphs.
  • Create pie charts.
  • Create histograms.
  • Display trends and patterns in data.

Installing Matplotlib

Matplotlib is usually available in Google Colab. If you need to install it locally, use:

pip install matplotlib

Importing Matplotlib

Use the following instruction to import the plotting tools:

import matplotlib.pyplot as plt

Creating a Simple Bar Chart

Imagine a shop records the number of products sold during a week.

import matplotlib.pyplot as plt

days = ["Monday", "Tuesday", "Wednesday", "Thursday"]
sales = [10, 15, 8, 20]

plt.bar(days, sales)

plt.title("Weekly Product Sales")
plt.xlabel("Days")
plt.ylabel("Products Sold")

plt.show()

This code creates a bar chart showing how many products were sold on each day.

Understanding the Code:

  • days: Stores the names of the days.
  • sales: Stores the number of products sold.
  • plt.bar(): Creates the bar chart.
  • plt.title(): Adds a title to the chart.
  • plt.xlabel(): Adds a label to the horizontal axis.
  • plt.ylabel(): Adds a label to the vertical axis.
  • plt.show(): Displays the chart.

5.5 Installing and Importing Data Analysis Libraries

Before using a Python library, you must make sure it is installed and imported correctly.

Let's look at the basic steps.

Step 1: Open a Python Environment

Open Google Colab, Jupyter Notebook, or Visual Studio Code.

Step 2: Install the Library If Necessary

For example, you can install the libraries using:

pip install numpy pandas matplotlib

In a Google Colab notebook, you can run the installation command with an exclamation mark at the beginning:

!pip install numpy pandas matplotlib

You usually do not need to install these libraries again if they are already available in your environment.

Step 3: Import the Libraries

Write the following instructions:

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

Now, you can use NumPy, Pandas, and Matplotlib in your Python program.

5.6 Using NumPy, Pandas, and Matplotlib Together

These three libraries can work together to help you analyse information.

Imagine a school wants to analyse the examination scores of five students.

Step 1: Create the Data

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

students = ["Ada", "Tunde", "Musa", "Grace", "John"]

scores = np.array([85, 70, 90, 65, 80])

Step 2: Organise the Data with Pandas

data = {
    "Student": students,
    "Score": scores
}

table = pd.DataFrame(data)

print(table)

Output:

  Student  Score
0     Ada     85
1   Tunde     70
2    Musa     90
3   Grace     65
4    John     80

Step 3: Calculate the Average with NumPy

average = np.mean(scores)

print("Average Score:", average)

Output:

Average Score: 78.0

Step 4: Create a Chart with Matplotlib

plt.bar(students, scores)

plt.title("Students' Examination Scores")
plt.xlabel("Students")
plt.ylabel("Scores")

plt.show()

The chart displays each student's examination score, making it easier to compare their performance.

In this example:

  • NumPy helped us work with the numerical scores.
  • Pandas organised the information into a table.
  • Matplotlib displayed the scores in a chart.

5.7 Comparing NumPy, Pandas, and Matplotlib

Library Main Purpose Example Use
NumPy Numerical calculations Calculating average scores.
Pandas Organising and analysing data Creating student records in a table.
Matplotlib Data visualisation Creating charts of examination scores.

5.8 Summary of the Module

In this module, you have learned:

  • Python libraries are collections of ready-made code.
  • NumPy is used for numerical calculations and working with arrays.
  • Pandas is used to organise, clean, and analyse data.
  • A Pandas DataFrame stores information in rows and columns.
  • Matplotlib is used to create charts and graphs.
  • Libraries can be installed and imported into Python programs.
  • NumPy, Pandas, and Matplotlib can work together in a data analysis project.

5.9 Practical Exercise

Open Google Colab or another Python environment and complete these activities:

  1. Import NumPy and create an array containing five numbers.
  2. Use NumPy to calculate the total and average of the five numbers.
  3. Import Pandas and create a DataFrame containing five students and their examination scores.
  4. Display the student names from your DataFrame.
  5. Use Pandas to calculate the average examination score.
  6. Import Matplotlib and create a bar chart showing the five students' scores.
  7. Add a title and labels to your chart.

Practical Challenge: Analyse a Small Shop's Sales

Imagine you are helping a shop owner in Nigeria analyse the number of products sold during four days.

Day Products Sold
Monday15
Tuesday20
Wednesday12
Thursday25

Your Task:

  1. Use NumPy to store the product sales figures.
  2. Calculate the total number of products sold.
  3. Calculate the average daily sales.
  4. Use Pandas to organise the days and sales figures into a DataFrame.
  5. Use Matplotlib to create a bar chart showing the daily sales.
  6. Identify the day with the highest sales.

What You Should Remember

Python libraries make data analysis easier. NumPy helps you work with numbers, Pandas helps you organise and analyse information, and Matplotlib helps you present information using charts.

As you continue learning Python, you will use these libraries to work with larger datasets and solve real-world problems.

๐Ÿ† 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.
โ†’