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.

# An array of toys
toys = np.array(['teddy bear', 'robot', 'doll', 'ball', 'yo-yo'])

# Print the number of toys
print("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.

# Our toys divided into two boxes
toys_boxes = np.array([['teddy bear', 'robot', 'car'], ['doll', 'ball', 'yo-yo']])

# Print the shape of the toy boxes
print("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.

import numpy as np
# An array of toys
toys = np.array(['teddy bear', 'robot', 'doll', 'ball', 'yo-yo', 'car'])

# Reshape the array
toys_boxes = toys.reshape(3, 2)

# Print the reshaped array
print(toys_boxes)
# [['teddy bear' 'robot']
#  ['doll' 'ball']
#  ['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:

# Let's create a list of alphabet blocks
blocks = np.array(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'])

# Reshape it into a 3x3 grid
puzzle = blocks.reshape(3, 3)

# Print the puzzle
print(puzzle)  
# [['A' 'B' 'C']
#  ['D' 'E' 'F']
#  ['G' 'H' 'I']]
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal