DEV Community

sanaipei
sanaipei

Posted on Edited on

Getting Started with NumPy: Understanding Numerical Computing in Python

By Lenapunya Sanaipei| Pastoralist in Tech

Introduction

As I continue exploring the Python data science ecosystem, one of the first libraries I want to revisit is NumPy.

NumPy is one of the foundational libraries in Python's scientific computing ecosystem. It provides tools for working with numerical data, performing mathematical operations and handling multidimensional arrays.

If you've worked with Python lists before, you might wonder why we need another way of storing collections of numbers.

Python already allows us to store information in lists, perform calculations and manipulate data.

So, what makes NumPy different?

That's what we'll explore in this article.

We'll start with the basics, understand how NumPy arrays work, explore their dimensions and properties, and perform some practical numerical operations.

I'll also include Python code that you can follow along with in Google Colab.

1. What is NumPy?

NumPy stands for Numerical Python.

It is an open-source Python library designed for numerical computing.

It provides a multidimensional array object called ndarray, alongside functions for performing mathematical operations, linear algebra, Fourier transforms and other numerical computations.

NumPy was created by Travis Oliphant and released in 2005.

One of its main strengths is its ability to perform efficient operations on large collections of numerical data.

Why do we need NumPy?

Python has built-in data structures such as lists and tuples that allow us to store collections of information.

For example:

incomes = [10000, 15000, 20000, 25000, 30000]
Enter fullscreen mode Exit fullscreen mode

This is a perfectly valid Python list.

We can calculate its average using:

average_income = sum(incomes) / len(incomes)

print(average_income)
Enter fullscreen mode Exit fullscreen mode

However, when working with large numerical datasets, we often need more specialised operations.

This is where NumPy becomes useful.

NumPy provides efficient array operations, mathematical functions and numerical tools that are particularly useful in data science.

2. Python Lists vs NumPy Arrays

Let's compare the two.

A Python list:

incomes = [10000, 15000, 20000, 25000, 30000]
Enter fullscreen mode Exit fullscreen mode

A NumPy array:

import numpy as np

incomes = np.array([10000, 15000, 20000, 25000, 30000])
Enter fullscreen mode Exit fullscreen mode

Both store our income values.

However, they behave differently when performing numerical operations.

Consider this:

numbers = [10, 20, 30]

print(numbers * 2)
Enter fullscreen mode Exit fullscreen mode

Output:

[10, 20, 30, 10, 20, 30]
Enter fullscreen mode Exit fullscreen mode

Why?

Because multiplying a Python list by an integer repeats the list.

Now let's try NumPy:

import numpy as np

numbers = np.array([10, 20, 30])

print(numbers * 2)
Enter fullscreen mode Exit fullscreen mode

Output:

[20 40 60]
Enter fullscreen mode Exit fullscreen mode

This time, every element has been multiplied by two.

This is one of the important differences between Python lists and NumPy arrays.

Why is NumPy generally faster?

NumPy arrays are designed for numerical computation.

They generally store elements in contiguous memory blocks, making numerical data access more efficient.

They also use optimised operations implemented largely in compiled languages such as C.

Another important concept is vectorisation.

Vectorisation allows us to perform operations across entire arrays without writing explicit Python loops for each element.

For example:

incomes = np.array([10000, 15000, 20000])

increased_incomes = incomes * 1.10

print(increased_incomes)
Enter fullscreen mode Exit fullscreen mode

Output:

[11000. 16500. 22000.]
Enter fullscreen mode Exit fullscreen mode

We have increased every income value by 10%.

This is particularly useful when working with large numerical datasets.

The exact performance advantage depends on the operation, data size and implementation. NumPy is not automatically faster for every task.

3. Understanding NumPy Arrays

The central data structure in NumPy is called an ndarray.

The name stands for N-dimensional array.

An array is a collection of elements organised into one or more dimensions.

Let's understand these dimensions.

3.1 Zero-dimensional array (0D)

A zero-dimensional array contains a single value.

For example:

import numpy as np

value = np.array(25)

print(value)
Enter fullscreen mode Exit fullscreen mode

Output:

25
Enter fullscreen mode Exit fullscreen mode

We can inspect its dimensions:

print(value.ndim)
Enter fullscreen mode Exit fullscreen mode

Output:

0
Enter fullscreen mode Exit fullscreen mode

Why is it zero-dimensional?

Because the array contains one value without any row or column structure.

Think of it as a single numerical observation.

3.2 One-dimensional array (1D)

A one-dimensional array contains elements arranged along one axis.

For example:

incomes = np.array([10000, 15000, 20000, 25000])

print(incomes)
Enter fullscreen mode Exit fullscreen mode

Output:

[10000 15000 20000 25000]
Enter fullscreen mode Exit fullscreen mode

This resembles a single row of numbers.

We can inspect its dimension:

print(incomes.ndim)
Enter fullscreen mode Exit fullscreen mode

Output:

1
Enter fullscreen mode Exit fullscreen mode

A practical example could be a collection of household income observations.

3.3 Two-dimensional array (2D)

A two-dimensional array has two axes, commonly represented as rows and columns.

Imagine we have collected monthly income observations from three households.

monthly_income = np.array([
    [10000, 12000, 15000],
    [20000, 22000, 25000],
    [15000, 18000, 21000]
])

print(monthly_income)
Enter fullscreen mode Exit fullscreen mode

Output:

[[10000 12000 15000]
 [20000 22000 25000]
 [15000 18000 21000]]
Enter fullscreen mode Exit fullscreen mode

We can represent this as a table:

Household January February March
A 10,000 12,000 15,000
B 20,000 22,000 25,000
C 15,000 18,000 21,000

Check its dimension:

print(monthly_income.ndim)
Enter fullscreen mode Exit fullscreen mode

Output:

2
Enter fullscreen mode Exit fullscreen mode

This is a 2D array because it has rows and columns.

3.4 Three-dimensional array (3D)

A three-dimensional array introduces another axis.

Imagine we have income observations for three households across two different years, with three monthly observations per year.

yearly_income = np.array([
    [
        [10000, 12000, 15000],
        [11000, 13000, 16000]
    ],
    [
        [20000, 22000, 25000],
        [21000, 23000, 26000]
    ],
    [
        [15000, 18000, 21000],
        [16000, 19000, 22000]
    ]
])

print(yearly_income.ndim)
Enter fullscreen mode Exit fullscreen mode

Output:

3
Enter fullscreen mode Exit fullscreen mode

We now have three dimensions:

  • Household.
  • Year.
  • Month.

This illustrates how NumPy can organise more complex numerical data.

Higher-dimensional arrays are also important in image processing, scientific computing and machine learning.

4. Creating NumPy Arrays

Now that we understand what arrays are, let's learn how to create them.

First, we import NumPy.

import numpy as np
Enter fullscreen mode Exit fullscreen mode

The import statement loads the library.

The as np part gives NumPy a shorter name.

This is the standard convention used throughout the Python data science ecosystem.

Creating an array using np.array()

numbers = np.array([10, 20, 30, 40, 50])

print(numbers)
Enter fullscreen mode Exit fullscreen mode

Here:

  • numbers is the variable holding our array.
  • np.array() is the NumPy function that creates the array.
  • The values inside the square brackets are our original data.

We can also create arrays from nested Python lists.

numbers = np.array([
    [10, 20, 30],
    [40, 50, 60]
])

print(numbers)
Enter fullscreen mode Exit fullscreen mode

This creates a two-dimensional array.

5. Understanding NumPy Array Properties

Creating an array is only the beginning.

When working with datasets, we need to understand their structure.

NumPy provides several properties that help us inspect an array.

Let's use this example:

sales = np.array([
    [12000, 15000, 18000],
    [22000, 25000, 30000],
    [14000, 16000, 19000]
])
Enter fullscreen mode Exit fullscreen mode
5.1 ndim - Number of dimensions
print(sales.ndim)
Enter fullscreen mode Exit fullscreen mode

Output:

2
Enter fullscreen mode Exit fullscreen mode

The ndim property tells us how many dimensions an array has.

In this case, we have a two-dimensional array.

5.2 shape - Structure of the array

print(sales.shape)
Enter fullscreen mode Exit fullscreen mode

Output:

(3, 3)
Enter fullscreen mode Exit fullscreen mode

The result tells us that the array has three rows and three columns.

For a two-dimensional array, the shape is represented as:

(rows, columns)
Enter fullscreen mode Exit fullscreen mode

5.3 size - Total number of elements

print(sales.size)
Enter fullscreen mode Exit fullscreen mode

Output:

9
Enter fullscreen mode Exit fullscreen mode

There are nine numerical observations in the array.

5.4 dtype - Data type of elements
print(sales.dtype)
Enter fullscreen mode Exit fullscreen mode

Output might be:

int64
Enter fullscreen mode Exit fullscreen mode

This tells us the data type NumPy uses to represent the array's elements.

Depending on the environment, you may see a different integer type.

Understanding data types becomes important when preparing datasets for mathematical operations and machine learning.

Putting everything together
print("Dimensions:", sales.ndim)
print("Shape:", sales.shape)
print("Total elements:", sales.size)
print("Data type:", sales.dtype)
Enter fullscreen mode Exit fullscreen mode

This gives us a quick overview of the array.

6. Performing Mathematical Operations with NumPy

NumPy is particularly useful when we need to perform numerical operations.

Let's create a simple dataset inspired by household income observations.

household_income = np.array([10000, 15000, 20000, 25000, 30000])
Enter fullscreen mode Exit fullscreen mode
Calculating the total
print(np.sum(household_income))
Enter fullscreen mode Exit fullscreen mode
Calculating the average
print(np.mean(household_income))
Enter fullscreen mode Exit fullscreen mode
Finding the minimum value
print(np.min(household_income))
Enter fullscreen mode Exit fullscreen mode
Finding the maximum value
print(np.max(household_income))
Enter fullscreen mode Exit fullscreen mode
Calculating the median
print(np.median(household_income))
Enter fullscreen mode Exit fullscreen mode

These functions allow us to perform common descriptive calculations.

However, there is an important distinction between calculating a statistic and interpreting it.

For example, the average household income does not necessarily tell us whether most households earn around that amount.

Income data can be skewed by a small number of households with particularly high incomes.

This is why we need to understand distributions and other statistical measures, not just calculate averages.

7. Practical Application: Working with Household Data

Let's bring everything together.

Imagine we are conducting a hypothetical research exercise involving household income observations in an Ilchamus community setting.

Our objective is to explore a small collection of household income figures.

For this exercise, we'll use entirely illustrative numbers. They are not actual Ilchamus household income statistics.

import numpy as np

# Illustrative household income observations
household_income = np.array([
    12000,
    18000,
    15000,
    25000,
    30000,
    22000,
    17000,
    28000
])

# Basic analysis
total_income = np.sum(household_income)

average_income = np.mean(household_income)

median_income = np.median(household_income)

minimum_income = np.min(household_income)

maximum_income = np.max(household_income)

# Display the results
print("Total:", total_income)
print("Average:", average_income)
print("Median:", median_income)
print("Minimum:", minimum_income)
print("Maximum:", maximum_income)
Enter fullscreen mode Exit fullscreen mode

What have we done?

We created an array containing household income observations and used NumPy to calculate descriptive statistics.

But let's think beyond the code.

What does the average actually tell us?

Is the median different from the average?

Are the observations representative of the wider community?

What other variables would we need to understand household income patterns?

For instance, we might need information about income sources, livestock ownership, agricultural production, household size, location and the period during which income was recorded.

These questions remind us that numerical computations are only one part of data analysis.

The quality of our conclusions depends on the quality of the data, the research design and how we interpret the results.

8. Why NumPy Matters in Data Science

NumPy is important because it provides numerical computing capabilities that are used throughout the Python ecosystem.

Several popular libraries build on or integrate with NumPy.

For example:

  • Pandas: Uses NumPy extensively in its numerical data structures and operations.
  • Matplotlib: Works with NumPy arrays when creating visualisations.
  • SciPy: Builds on NumPy for scientific computing.
  • Scikit-learn: Uses NumPy arrays extensively in its machine learning workflows.

Understanding NumPy therefore makes it easier to understand what happens when working with other data science libraries.

Conclusion

NumPy is much more than a library for creating arrays.

It provides a foundation for numerical computing in Python and helps us work efficiently with numerical data.

In this article, we've explored what NumPy is, why it is useful, how its arrays work, the different dimensions and some of the properties and mathematical operations we can perform.

The next step is to take these concepts into a practical Google Colab notebook and experiment with arrays ourselves.

As I continue this journey from Data Analytics towards Data Science, I want to keep reminding myself that knowing the functions is only part of the process.

Understanding the data, asking the right questions and knowing why we are performing an operation are equally important.

The goal is not to become someone who can simply execute Python code. The goal is to become someone who understands the problem, knows which tools to use and can turn data into meaningful information.


Series: From Data Analytics to Data Science with Python

Previous article: From Data Analytics to Data Science: Exploring the Python Data Science Ecosystem

Next practical step: NumPy Arrays in Google Colab

Author: Sanaipei Lenapunya

Identity: Pastoralist in Tech

Website: https://sanaipei.me

Top comments (1)

Collapse
 
lesanaipei profile image
sanaipei •

I love python🥰