Lesson 4

Array Shape and Reshape

Understanding Shape and Reshape

Hello, Space Voyager! Today we're focusing on Array Shape and Reshape in NumPy. Understanding an array's shape is like knowing the size of a box—it tells us how we can manipulate it. Meanwhile, reshaping an array is like changing a box's dimensions to meet our needs.

Understanding Shapes

The shape of an array is its dimensions, which are the sizes along each of its axes. Thus, understanding an array's shape helps us comprehend its structure. The concept of reshaping allows us to adjust the array's dimensions.

Investigating Array Shape

NumPy provides an easy way to find an array's shape with the shape attribute. It's like getting the length of a list of toys in a box, which is the total number of toys, or the size of our array.

Python
1# An array of toys 2toys = np.array(['teddy bear', 'robot', 'doll', 'ball', 'yo-yo']) 3 4# Print the number of toys 5print("Number of toys:", toys.shape) # Number of toys: (5,)

With a 2D array, the shape attribute returns a pair of numbers: the number of rows and columns.

Python
1# Our toys divided into two boxes 2toys_boxes = np.array([['teddy bear', 'robot', 'car'], ['doll', 'ball', 'yo-yo']]) 3 4# Print the shape of the toy boxes 5print("Shape of toy boxes:", toys_boxes.shape) # Shape of toy boxes: (2, 3)
Reshaping Array

With NumPy's reshape method, we can flexibly change an array's shape without altering its data.

Python
1import numpy as np 2# An array of toys 3toys = np.array(['teddy bear', 'robot', 'doll', 'ball', 'yo-yo', 'car']) 4 5# Reshape the array 6toys_boxes = toys.reshape(3, 2) 7 8# Print the reshaped array 9print(toys_boxes) 10# [['teddy bear' 'robot'] 11# ['doll' 'ball'] 12# ['yo-yo' 'car']]
Real Life Examples: Reshaping Arrays

Reshaping arrays can be powerful in real-life scenarios. For example, if we're arranging alphabet blocks into a grid for a word puzzle, or if we're organizing family age data from a 1D array into a 2D array of generations and siblings. Here is the first example in code:

Python
1# Let's create a list of alphabet blocks 2blocks = np.array(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']) 3 4# Reshape it into a 3x3 grid 5puzzle = blocks.reshape(3, 3) 6 7# Print the puzzle 8print(puzzle) 9# [['A' 'B' 'C'] 10# ['D' 'E' 'F'] 11# ['G' 'H' 'I']]
Lesson Summary and Practice

Well done, coder! You learned about array shape and reshaping in NumPy, practiced with real examples, and solidified your understanding. Now, let's strengthen this knowledge with hands-on practice exercises. Remember, real coding can't be learned by watching. So, get ready for some coding!

Enjoy this lesson? Now it's time to practice with Cosmo!

Practice is how you turn knowledge into actual skills.