Image

How to Install NumPy on Raspberry Pi & Create a Simple Project

If you click our links and make a purchase, we may earn an affiliate commission. Learn more

Python comes preinstalled on Raspberry Pi OS, giving us the flexibility to build powerful projects right out of the box. But when it comes to numerical computing, NumPy is one of the most essential libraries that unlock Python’s full potential. This post will give you a step-by-step guide for installing NumPy on your system, followed by a simple, hands-on project to demonstrate its practical use.

NumPy can be installed on a Raspberry Pi using either the PIP package manager for Python or the APT package manager.

I will provide an overview of NumPy and its applications, followed by detailed installation steps. Finally, I will guide you through creating a simple project using both NumPy and Matplotlib to visualize data.

If you’re like me and sometimes mix up syntax between programming languages, I’ve got just the thing for you. I’ve put together a Python cheat sheet with all the essential syntax in one place, so you can keep it handy and avoid any confusion. Download it here for free!

What is NumPy?

NumPy, short for Numerical Python, is a powerful Python library that supports working with multidimensional arrays and matrices and a collection of mathematical functions to manipulate these data structures.

Image

If you are considering entering fields like Data Science or Machine Learning, having a solid understanding of NumPy is essential. Why is NumPy so good?

NumPy handles numerical operations far more efficiently than Python lists or loops. Moreover, it comes with a wide range of built-in functions that you can easily integrate into your projects, saving time and improving performance.

As mentioned, NumPy is useful for Data Science and Machine Learning projects. But let’s dive into some specific, hands-on projects you can explore with your Raspberry Pi that take advantage of NumPy’s powerful capabilities.

  • Facial Recognition System:
    An exciting project you can take on with your Raspberry Pi and NumPy is building a Facial Recognition System. By combining NumPy with powerful libraries like OpenCV, you can preprocess and analyze images captured by your Pi to recognize faces.

    NumPy’s ability to handle complex matrix and array operations on pixel data makes it an essential tool for performing the calculations required in facial recognition algorithms.
  • Real-Time Sensor Data Analysis:
    Another fascinating project you can explore with your Raspberry Pi and NumPy is Real-Time Sensor Data Analysis. Connecting sensors like temperature, humidity, or motion detectors to your Pi, allows you to collect real-time data and use NumPy to process it.
  • Image Processing and Manipulation:
    It might be slightly more complex, but you can capture images with the Pi camera, and use NumPy to perform tasks like filtering, edge detection, and color manipulation. Since images can be treated as arrays, NumPy’s fast array operations make it highly efficient for processing and transforming images.

Excited? Let’s see how to get started with NumPy on your Raspberry Pi now.

Pre-requisites to Install NumPy on Raspberry Pi

There are not many requirements in terms of hardware and software to use NumPy, you can use an existing installation. Just make sure you have:

  • Any Raspberry Pi model: You can use any Raspberry Pi model to install and use NumPy. All you need is a Linux distro running on the board. However, older models like the Raspberry Pi 1, and Pi Zero have limited processing power and memory to handle complex NumPy projects. Check my recommended products here.
  • SD card or USB stick for the OS: You will need this for installing the operating system. I highly recommend having an 8GB SD card or USB stick. Here is the SD card I currently recommend (Amazon).
  • Raspberry Pi OS: In this post, I’ll be using the official Raspberry Pi OS, but you can use any Linux distribution supported by Raspberry Pi. We also have a post that highlights 15 different operating systems you can install on your Raspberry Pi.
  • Internet access: Your Raspberry Pi must be connected to the Internet for this project. Check out our post on configuring Wi-Fi on the Raspberry Pi, where we cover six different methods that’ll get you connected.

Installing NumPy on the Raspberry Pi

You should now understand NumPy and what you need to have it running on the Raspberry Pi. Now, let’s look at the step-by-step process.

Grab my Python cheat sheet!
If like me, you always mix the languages syntax, download my cheat sheet for Python here!
Download now

Update the Operating System

The first thing you need to do is update the operating system.

If you are running the official Raspberry Pi OS or any Debian-based distribution like Ubuntu or Kali, you can use the commands below to update the system packages:
sudo apt update
sudo apt upgrade

Are you a bit lost in the Linux command line? Check this article first for the most important commands to remember and a free downloadable cheat sheet so you can have the commands at your fingertips.

Install Python 3.x

NumPy is a Python library, so Python is mandatory to get started – specifically Python 3 or higher. Like many other Linux distributions, Python comes preinstalled on Raspberry Pi OS, but you can verify that using the command below:
python3 --version

Image

In my case, Python 3.9.2 is already installed. Your version may be different, but as long as it’s Python 3 or higher, you’re all set and ready to proceed.

If you don’t have Python3 installed, you can install it using the commands below:
sudo apt update
sudo apt install python3

Install pip (Python Package Installer)

Pip is used to install Python libraries like NumPy. If it’s not already installed, you can install pip using:
sudo apt install python3-pip

Image

Install Build Tools (Optional, but Recommended)

Sometimes NumPy may need to be built from source on ARM architectures (like the Raspberry Pi), so it’s useful to install essential build tools:
sudo apt install build-essential

Image

Install Virtual Environment (Optional, For Isolated Installation)

Use a virtual environment to isolate your NumPy installation from your system’s main Python environment.

A virtual environment is a self-contained Python environment that allows you to install packages and dependencies without affecting your system-wide Python installation.

Grab my Python cheat sheet!
If like me, you always mix the languages syntax, download my cheat sheet for Python here!
Download now

I have a full tutorial on this topic (check it here), but to set up a virtual environment, you first need to install the venv package:
sudo apt install python3-venv

Next, create your virtual environment with the following command:
python3 -m venv myenv

Then activate it:
source myenv/bin/activate

Once activated, any packages you install, including NumPy, will be contained within this environment, keeping your system clean and organized.

Image

Install Numpy

Once you have everything ready, install NumPy on your system using the command below. In my case, I am working in a virtual environment:
pip3 install numpy

Image

Note: You might come across other sources suggesting using the command below to install NumPy:
sudo apt install python3-numpy

Even though it might work, I don’t recommend it. This method installs NumPy directly from the Raspberry Pi OS repositories. However, the version of NumPy available via apt may not always be the latest version, as it depends on the version in the repository.

Verify Numpy Installation

After successfully installing NumPy, you can verify using the command below:
python3 -c "import numpy; print(numpy.__version__)"

In my case, NumPy version 2.0.2 is installed on my system. The version number you see might differ, depending on when you’re following this tutorial, as updates are regularly released.

Image

Project: Visualizing data using NumPy and Matplotlib

Now let’s look at a simple project you can carry out with NumPy and another popular Python library – Matplotlib.

Lost in the terminal? Grab My Pi Cheat-Sheet!
Download the free PDF, keep it open, and stop wasting time on Google.
Download now

Matplotlib is a Python library used for creating visualizations like graphs and charts to make data easier to understand.

Imagine you need to analyze student performance and want to make the data easier to understand with a visual graph. This project will show how to use NumPy for basic calculations and Matplotlib to turn that data into a clear graph.

Set Up Your Environment

We have a tutorial on installing and using Matplotlib on the Raspberry Pi. However, if you have been following this tutorial step-by-step, you can install it using the command below:
pip3 install matplotlib

One more thing that we will need to install is the Jupyter Notebook.

Jupyter Notebook is an interactive web-based tool that allows you to write and run code, visualize data, and document your work in one place.

You can install Jupyter Notebook using the command below:
pip3 install notebook

Launch Jupyter

Once Jupyter is successfully installed, launching it is straightforward. Simply type the following command in your terminal:
jupyter notebook

As it starts up, you’ll see logs appear in the terminal. Keep an eye out for a line that says, “To access the server, open this file in a browser,” or “Copy and paste one of these URLs.” Once you spot the URL, open it in your web browser, and you should see a window that looks similar to the one below.

To create a new file, click on the “File” menu and select “Notebook.”

Image

Related: Remote Python Development on Raspberry Pi

Write the code

Lost in the terminal? Grab My Pi Cheat-Sheet!
Download the free PDF, keep it open, and stop wasting time on Google.
Download now

We’ll go straight to the point, so if you need a refresher on the Python syntax, you may want to check my Python basics tutorial first, or even better, read my book “Master Python on Raspberry Pi“.

Below is the code that we will use for this project. I have divided it into various sections so you can understand it better.

  • Import the libraries:
    # Import the NumPy library for numerical operations
    import numpy as np
    # Import Matplotlib for data visualization
    import matplotlib.pyplot as plt
  • Generate dummy data using NumPy:
    #Defining Dummy Data
    #Create a NumPy array of student scores
    scores = np.array([85, 92, 78, 90, 88, 76, 95, 89, 84, 91])
  • Calculate the statistics:
    #Calculate mean, median, variance, and standard deviation of the scores
    mean_score = np.mean(scores)
    median_score = np.median(scores)
    variance_score = np.var(scores)
    std_deviation_score = np.std(scores)
  • Print the results:
    #Print the list of student scores and calculated statistics print("Student Scores:", scores) print(f"Mean Score: {mean_score:.2f}")
    print(f"Median Score: {median_score:.2f}")
    print(f"Variance: {variance_score:.2f}")
    print(f"Standard Deviation: {std_deviation_score:.2f}")
  • Create a Bar Chart for Visualization:
    #Generate student names for the x-axis labels
    student_names = [f'Student {i+1}' for i in range(len(scores))]
    #Create a bar chart with student names and their scores
    plt.bar(student_names, scores, color='skyblue')
    #Add horizontal lines for mean and median scores
    plt.axhline(mean_score, color='red', linestyle='--', label=f'Mean Score: {mean_score:.2f}')
    plt.axhline(median_score, color='green', linestyle='--', label=f'Median Score: {median_score:.2f}')
  • Add labels and titles to the bar chart:
    plt.title('Student Performance') # Set the title of the chart
    plt.xlabel('Students') # Label the x-axis
    plt.ylabel('Scores') # Label the y-axis
    plt.ylim(0, 100) # Set the limits for the y-axis
    plt.legend() # Display the legend
    plt.grid(axis='y') # Add grid lines to the y-axis for better readability
  • Display the plot:
    plt.show() # Show the bar chart

After entering this code in your notebook, click the play button at the top to execute it. You should see a bar chart appear below, displaying the student performance data as shown in the example below.

Image

Now that NumPy is successfully installed on your Raspberry Pi, you’re ready to dive deeper into its powerful features. You can start using it in your projects like the ones I mentioned above.

To learn more and expand your skills with NumPy, check the official NumPy documentation, which is a great place to explore tutorials, functions, and advanced usage.

You can also check these other articles I have for your Python projects:


🛠 This tutorial doesn't work anymore? Report the issue here, so that I can update it!

If you prefer watching videos instead of reading tutorials, you’ll love the RaspberryTips Community. I post a new lesson every month (only for members), and you can unlock them all with a 7-day trial for $1.

Frequently Asked Questions

Can NumPy work with images?

NumPy can work with images by treating them as arrays of pixel values. Each pixel in an image is represented by numerical data. NumPy’s efficient array operations make it ideal for image manipulation, filtering, and transformations.

It is often used alongside libraries like OpenCV or Pillow to process images in Python.

What’s the difference between a Python list and a NumPy array?

NumPy arrays are faster, more efficient, and designed for numerical operations, while Python lists are more flexible but slower and less suited for large-scale computations.

Whenever you’re ready, here are other ways I can help you:

Test Your Raspberry Pi Level (Free): Not sure why everything takes so long on your Raspberry Pi? Take this free 3-minute assessment and see what’s causing the problems.

The RaspberryTips Community: Need help or want to discuss your Raspberry Pi projects with others who actually get it? Join the RaspberryTips Community and get access to private forums, exclusive lessons, and direct help (try it for just $1).

Master your Raspberry Pi in 30 days: If you are looking for the best tips to become an expert on Raspberry Pi, this book is for you. Learn useful Linux skills and practice multiple projects with step-by-step guides.

Master Python on Raspberry Pi: Create, understand, and improve any Python script for your Raspberry Pi. Learn the essentials step-by-step without losing time understanding useless concepts.

You can also find all my recommendations for tools and hardware on this page.

Similar Posts