Learn NumPy · 6/15

Shape-Shifting: Array Manipulation

5 min read

Shape-Shifting: Array Manipulation манипуляция массивами

Welcome, data wrangler! 🤠 Today, we're diving into the art of "Shape-Shifting" with NumPy arrays. Think of it like being a data clay sculptor; you have a lump of data (your array), and you need to mold it into different shapes and sizes to fit your needs. This is a fundamental skill in data science and machine learning, as algorithms often expect data in a very specific format.


1. Changing Dimensions: The reshape() Method 📐

The Problem: You have a one-dimensional array of, say, 12 elements, but for a particular calculation, you need to represent this as a 3x4 two-dimensional grid (a matrix). How do you rearrange these elements without manually creating a new array?

The Solution: The reshape() method is your go-to tool for this. It allows you to change the shape of an array without changing its data.

Imagine you have a long string of 12 beads, and you want to arrange them into a rectangular box with 3 rows and 4 columns. reshape() does exactly that with your data.

python
import numpy as np

# A 1D array with 12 elements
long_array = np.arange(12)
print("Original array:")
print(long_array)
# Output: [ 0  1  2  3  4  5  6  7  8  9 10 11]

# Reshape it into a 3x4 matrix
reshaped_array = long_array.reshape(3, 4)
print("\nReshaped array (3x4):")
print(reshaped_array)
# Output:
# [[ 0  1  2  3]
#  [ 4  5  6  7]
#  [ 8  9 10 11]]

🤔 Under the Hood: When you use reshape(), NumPy is clever about memory. If possible, it will create a "view" of the original array, meaning the new reshaped array is just looking at the original data in a different way. Modifying the view will change the original array. However, if a view isn't possible (due to memory layout), reshape() will create a copy.

💡 Fun Fact: The total number of elements must remain the same. You can't reshape an array of 12 elements into a 3x5 matrix because that would require 15 elements. NumPy will throw a ValueError if you try!


2. Flattening Data: flatten() vs. ravel() 🥞

The Problem: Now, let's reverse the situation. You have a multi-dimensional array, like our 3x4 matrix from before, and you need to squash it back into a single, one-dimensional line of data. This is a common preprocessing step for feeding data into certain machine learning algorithms.

The Solution: NumPy gives you two main ways to do this: flatten() and ravel(). They both achieve the same result of creating a 1D array, but they have one crucial difference.

Let's think of it like making a document. flatten() is like "Save As..." which creates a completely new, independent copy. ravel() is more like creating a shortcut or a pointer to the original document.

python
import numpy as np

# Our 3x4 matrix
matrix = np.arange(12).reshape(3, 4)
print("Original matrix:")
print(matrix)

# Using flatten() - creates a copy
flattened_array = matrix.flatten()
print("\nFlattened array (using flatten()):")
print(flattened_array)

# Using ravel() - creates a view (if possible)
raveled_array = matrix.ravel()
print("\nRaveled array (using ravel()):")
print(raveled_array)

# Let's modify the raveled array and see what happens to the original
raveled_array[0] = 99
print("\nOriginal matrix after modifying the raveled array:")
print(matrix)
# Output:
# [[99  1  2  3]
#  [ 4  5  6  7]
#  [ 8  9 10 11]]

As you can see, changing the raveled_array also changed the original matrix! This didn't happen with flatten().

Industry Practice: Use ravel() when you can because it's generally faster as it doesn't have to create a new copy of the data in memory. However, if you need to be sure that your original array won't be accidentally changed, use flatten().


3. Expanding Dimensions: Using np.newaxis and expand_dims() ➕

The Problem: You have a simple 1D array, but a function or a library (like those used in deep learning) expects your data to have an extra dimension, for example, to represent a "batch" of a single item. How do you add a new dimension to an array?

The Solution: NumPy offers np.newaxis and the expand_dims() function for this purpose. They both allow you to insert a new axis into an array's shape.

Imagine you have a single line of people. To make them a "row" in a formation, you add a new dimension.

python
import numpy as np

# A simple 1D array
simple_array = np.array([1, 2, 3])
print("Original array and its shape:")
print(simple_array)
print(simple_array.shape) # Output: (3,)

# Using np.newaxis to create a row vector
row_vector = simple_array[np.newaxis, :]
print("\nRow vector and its shape:")
print(row_vector)
print(row_vector.shape) # Output: (1, 3)

# Using np.newaxis to create a column vector
col_vector = simple_array[:, np.newaxis]
print("\nColumn vector and its shape:")
print(col_vector)
print(col_vector.shape) # Output: (3, 1)

# Using expand_dims() - a more explicit way
expanded_array = np.expand_dims(simple_array, axis=0) # axis=0 adds a new dimension at the beginning
print("\nExpanded array using expand_dims() and its shape:")
print(expanded_array)
print(expanded_array.shape) # Output: (1, 3)

Practicality is Key: This technique is extremely common in machine learning when you need to feed a single data point into a model that expects a batch of data. By adding a new axis, you're essentially telling the model, "Here's a batch of size 1."


4. Transposing Arrays: Swapping Axes 🔄

The Problem: You have a matrix, say a 3x4, and you need to flip it so that it becomes a 4x3 matrix. This operation, where rows become columns and columns become rows, is called transposing. It's a fundamental operation in linear algebra.

The Solution: NumPy makes transposing incredibly easy with the .T attribute or the transpose() method.

Think of a spreadsheet. Transposing is like taking all the data from the rows and pasting it into the columns, and vice-versa.

python
import numpy as np

# A 3x4 matrix
matrix = np.arange(12).reshape(3, 4)
print("Original matrix:")
print(matrix)
# Output:
# [[ 0  1  2  3]
#  [ 4  5  6  7]
#  [ 8  9 10 11]]

# Transposing using the .T attribute
transposed_matrix = matrix.T
print("\nTransposed matrix:")
print(transposed_matrix)
# Output:
# [[ 0  4  8]
#  [ 1  5  9]
#  [ 2  6 10]
#  [ 3  7 11]]

Did you know? Transposing a matrix twice gets you back to the original matrix. It's like flipping a pancake and then flipping it again!


📚 References for Extra Reading

Challenge

You are a data scientist preparing sensor data for a machine learning pipeline. You've received a raw, one-dimensional stream of 24 data points from a sensor. This stream represents 4 distinct trials, with each trial consisting of 6 consecutive data points.

Your task is to perform a series of manipulations to structure this data correctly for different stages of the pipeline.

  1. First, take the initial 1D sensor_data array and reshape it into a 2D array named trial_matrix. Each row in this matrix should represent one of the 4 trials.
  2. Next, for feature analysis, the data needs to be in a format where each column represents a feature (a data point at a specific time step) and each row represents a trial. Transpose trial_matrix to create a new array called feature_matrix.
  3. For a separate statistical summary, you need to isolate the first feature (the first column of feature_matrix) as a new 1D array. Create a new, completely independent 1D array named first_feature_flat from this first column. Modifications to first_feature_flat must not alter feature_matrix.
  4. Finally, a machine learning model needs to make a prediction on a single trial. Extract the third trial (index 2) from trial_matrix and transform it into a new array named model_input. This array must have the shape (1, 6) to be compatible with the model's batch processing input layer.

Expected result

Your code should correctly define four NumPy arrays: trial_matrix, feature_matrix, first_feature_flat, and model_input.

  1. trial_matrix should be a 4x6 NumPy array:
    inform7
    [[ 0,  1,  2,  3,  4,  5],
     [ 6,  7,  8,  9, 10, 11],
     [12, 13, 14, 15, 16, 17],
     [18, 19, 20, 21, 22, 23]]
  2. feature_matrix should be the 6x4 transpose of trial_matrix:
    inform7
    [[ 0,  6, 12, 18],
     [ 1,  7, 13, 19],
     [ 2,  8, 14, 20],
     [ 3,  9, 15, 21],
     [ 4, 10, 16, 22],
     [ 5, 11, 17, 23]]
  3. first_feature_flat should be a 1D array containing the first column of feature_matrix. It must be a separate copy in memory.
    angelscript
    [ 0,  6, 12, 18]
  4. model_input should be a 2D array with a shape of (1, 6), containing the data from the third trial.
    lua
    [[12, 13, 14, 15, 16, 17]]
python

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.