Hello! Welcome to your next lesson in the "Python Tools for AI and Data Manipulation" module.
In our last session, we set up a professional project structure using Poetry, ensuring our work is organized and reproducible. Now that our environment is ready, it's time to dive into the first and most fundamental library for numerical computing in Python: NumPy (Numerical Python).
The learning outcome for this lesson is to create and manipulate NumPy arrays, including indexing, slicing, and reshaping. Almost every major AI and data science library, including Pandas, Scikit-learn, and PyTorch, is built on top of NumPy. Its core data structure, the multidimensional array (ndarray), is the foundation for representing everything from datasets to model parameters. For you as a software engineer, you can think of a NumPy array as a super-powered, multi-dimensional array, optimized for mathematical operations on numerical data, offering significant performance gains over standard Python lists.
Let's start by adding NumPy to our project. In your terminal, navigate to the project directory you created in the last lesson and run:
poetry add numpy
Now, let's get to work.
1. The NumPy ndarray: The Foundation of Numerical Data
The heart of NumPy is the ndarray object. It's a table of elements, all of the same data type, and can have any number of dimensions. Before we start creating them, it's useful to understand their basic properties.
NumPy quickstart — NumPy v2.3 Manual
The official NumPy Quickstart guide is the best place to start. It introduces the ndarray object and its most important attributes.
Under the section titled 'The basics', read the array basics. Focus on understanding the five key attributes of an ndarray: ndim, shape, size, dtype, and itemsize. These are properties you will constantly check when debugging your code.
To recap, the main attributes are:
ndim: The number of dimensions (or axes). A vector is 1D, a matrix is 2D, and so on.shape: A tuple of integers indicating the size of the array in each dimension. A 3x4 matrix would have a shape of(3, 4).size: The total number of elements in the array. For a 3x4 matrix, the size is 12.dtype: The data type of the elements (e.g.,int64,float64). Unlike Python lists, all elements in a NumPy array must have the same type.
2. Creating NumPy Arrays
There are many ways to create arrays. You can convert them from Python lists or use built-in NumPy functions to generate arrays with placeholder or sequential data. These functions are highly efficient as they pre-allocate the necessary memory.
NumPy quickstart — NumPy v2.3 Manual
The NumPy Quickstart guide also provides a great overview of the most common array creation methods.
Read the 'Array creation' section. Pay close attention to creating arrays from lists with np.array(), and using generator functions like np.zeros(), np.ones(), np.arange(), and np.linspace().
Let's put this into practice. Here's a Python script summarizing these methods. You can create a file named numpy_basics.py and run it with poetry run python numpy_basics.py.
import numpy as np
# 1. Create a 1D array from a Python list
list_1d = [1, 2, 3, 4, 5]
array_1d = np.array(list_1d)
print(f"1D Array: {array_1d}")
print(f"Shape: {array_1d.shape}, Dtype: {array_1d.dtype}\n")
# 2. Create a 2D array from a list of lists
list_2d = [[1, 2, 3], [4, 5, 6]]
array_2d = np.array(list_2d)
print(f"2D Array:\n{array_2d}")
print(f"Shape: {array_2d.shape}, Dtype: {array_2d.dtype}\n")
# 3. Create an array of all zeros
zeros_array = np.zeros((2, 3)) # Shape is passed as a tuple
print(f"Zeros Array:\n{zeros_array}\n")
# 4. Create an array of all ones, specifying a different data type
ones_array = np.ones((3, 2), dtype=np.int16)
print(f"Ones Array:\n{ones_array}\n")
# 5. Create an array with a range of elements
range_array = np.arange(0, 10, 2) # Start, stop (exclusive), step
print(f"Range Array: {range_array}\n")
3. Accessing Data: Indexing and Slicing
Once you have an array, you need to be able to access and select subsets of its data. This is where indexing (accessing single elements) and slicing (accessing subsequences) come in. The syntax is similar to Python lists but extends elegantly to multiple dimensions.
How to Index, Slice and Reshape NumPy Arrays for ...
For a practical, machine learning-focused perspective on these operations, this article from Machine Learning Mastery is excellent.
Read the sections '2. Array Indexing' and '3. Array Slicing'. Focus on how the syntax array[row, column] works for 2D arrays and how the colon : is used to select entire rows or columns.
Indexing and Slicing in 1D
For a 1D array, this works just like a Python list.
array[0]gets the first element.array[-1]gets the last element.array[2:5]gets elements from index 2 up to (but not including) index 5.array[:3]gets the first 3 elements.array[-2:]gets the last 2 elements.
Indexing and Slicing in 2D
For 2D arrays (matrices), you use a comma to separate the dimension indices: array[row, column].
The following image provides a fantastic visual guide to how these operations work on a 2D grid.

Practical Slicing for Machine Learning
Slicing is not just an academic exercise; it's the primary way you'll prepare your data for a model. Two extremely common use cases are:
-
Separating Features (X) from the Target (y): In supervised learning, your dataset is typically a matrix where the last column is the value you want to predict (the target), and the preceding columns are your input features.
-
Splitting Data into Training and Testing Sets: You use a portion of your data to train the model and hold back the rest to test its performance.
The article you just read (LINK) shows exactly how to do this. Let's look at the code:
import numpy as np
# A sample dataset: 3 observations, 2 features, 1 target variable
data = np.array([
[11, 22, 1], # Feature 1, Feature 2, Target
[44, 55, 0],
[77, 88, 1]
])
# 1. Separate features (X) and target (y)
# Select all rows (:), and all columns except the last one (:-1)
X = data[:, :-1]
# Select all rows (:), and only the last column (-1)
y = data[:, -1]
print("Original Data:\n", data)
print("\nFeatures (X):\n", X)
print("\nTarget (y):\n", y)
# 2. Split into training and test sets (e.g., first 2 rows for train, rest for test)
split_point = 2
train_set = data[:split_point, :] # Select rows from start to split_point, and all columns
test_set = data[split_point:, :] # Select rows from split_point to end, and all columns
print("\nTraining Set:\n", train_set)
print("\nTest Set:\n", test_set)
Test your understanding!
You are given a NumPy array called dataset with the shape (100, 20), representing 100 samples and 20 features. Write a single line of code to create a new array called subset that contains only the last 5 features (columns) for the first 10 samples (rows).
Show answer
subset = dataset[:10, -5:]
_:10` slices the rows, selecting from the start up to index 10 (i.e., rows 0-9).-5:slices the columns, selecting from the 5th-to-last column to the end.
4. Changing the Array's Structure: Reshaping
Often, you'll have data in one shape, but the machine learning model you're using will expect it in another. For example, a 1D list of values might need to be converted into a 2D column vector. Reshaping allows you to change the shape of an array without changing its data. The total number of elements (size) must remain the same.
How to Index, Slice and Reshape NumPy Arrays for ...
The Machine Learning Mastery article concludes with a practical guide to reshaping, which is crucial for making your data compatible with various ML libraries.
Read the final section, '4. Array Reshaping'. Pay special attention to the examples of reshaping a 1D array to a 2D array and a 2D array to a 3D array, as these are very common requirements.
Let's look at the key scenarios.
import numpy as np
# Scenario 1: Reshaping a 1D array to a 2D column vector
# This is often required by scikit-learn models.
data_1d = np.array([11, 22, 33, 44, 55])
print(f"Original 1D shape: {data_1d.shape}")
# Reshape to a 2D array with 5 rows and 1 column
data_2d_col = data_1d.reshape((5, 1))
print(f"Reshaped to column vector:\n{data_2d_col}")
print(f"New shape: {data_2d_col.shape}\n")
# A useful trick: use -1 and NumPy will infer the dimension
# This is more robust as you don't need to hardcode the number of rows.
data_2d_col_auto = data_1d.reshape((-1, 1))
print(f"Reshaped automatically:\n{data_2d_col_auto}")
print(f"New shape: {data_2d_col_auto.shape}\n")
# Scenario 2: Reshaping for sequence data (e.g., for Transformers or LSTMs)
# Let's say we have 3 samples, each with 2 time steps.
data_2d_seq = np.array([[10, 20], [30, 40], [50, 60]])
print(f"Original 2D sequence shape: {data_2d_seq.shape}")
# Many deep learning models expect a 3D array: (samples, timesteps, features)
# Here, we have 1 feature per time step.
data_3d_seq = data_2d_seq.reshape((data_2d_seq.shape[0], data_2d_seq.shape[1], 1))
print(f"Reshaped to 3D sequence:\n{data_3d_seq}")
print(f"New 3D shape: {data_3d_seq.shape}")
The reshape(-1, ...) pattern is particularly useful and common in professional code because it adapts automatically if the size of your initial array changes.
Conclusion
Congratulations! You've just covered the fundamental operations for working with NumPy arrays. These skills are the absolute bedrock of data manipulation for AI.
Here are the key takeaways from this lesson:
- NumPy's
ndarrayis the core data structure for numerical operations in Python, offering efficiency and power. - You can create arrays from Python lists (
np.array) or using generator functions likenp.zeros,np.ones, andnp.arange. - Indexing (
arr[r, c]) and Slicing (arr[:r, c:]) are the essential tools for selecting and extracting data, crucial for tasks like separating features from targets. - Reshaping (
arr.reshape()) allows you to change an array's dimensions to meet the input requirements of AI/ML libraries, without altering the underlying data.
Next up:
So far, we've focused on creating and structuring data. The real power of NumPy, however, comes from its ability to perform fast mathematical computations. In the next lesson, we will explore vectorized operations, learning how NumPy allows you to perform complex calculations on entire arrays at once, without writing slow Python loops. This is the key to writing efficient and readable AI code.