At the heart of NumPy is its primary data structure: the N-dimensional array, often referred to as ndarray
. Think of an ndarray
as a grid or table containing items of the same data type, like integers or floating-point numbers. This uniformity is a significant reason why NumPy operations are so fast.
Why not just use standard Python lists? While Python lists are flexible, they are not optimized for numerical operations across entire collections of numbers. Performing mathematical operations on list elements typically requires explicit loops in Python, which can be slow for large datasets. Furthermore, lists can hold elements of different types, adding overhead.
NumPy arrays, on the other hand, are stored in a more efficient way in memory (as a contiguous block) and many complex operations (like element-wise addition or multiplication) are performed by pre-compiled C code operating behind the scenes. This makes NumPy incredibly fast for the mathematical computations common in machine learning and data analysis.
An ndarray
has a shape
, which tells you the size of the array along each dimension, and a dtype
, which describes the data type of the elements within the array.
The "N-dimensional" aspect means arrays can have multiple dimensions:
Let's look at a simple example. To use NumPy, you first need to import the library. The standard convention is to import it using the alias np
:
import numpy as np
# Create a NumPy array from a Python list
list_a = [1, 2, 3, 4, 5]
vector_a = np.array(list_a)
# Print the array and its type
print(vector_a)
print(type(vector_a))
Running this code will output:
[1 2 3 4 5]
<class 'numpy.ndarray'>
Notice how the output [1 2 3 4 5]
doesn't have commas like a Python list. This is the standard representation of a NumPy array. We've created a 1-D array (a vector) from a simple Python list.
This ndarray
object is the foundation upon which we will build our understanding of linear algebra computations in Python. In the following sections, we will learn how to create arrays in various ways, access their elements, perform mathematical operations, and manipulate their shapes.
© 2025 ApX Machine Learning