NumPy · Lesson 1.1

Shape and reshape

Arrays with rows and columns, how to read their shape, and how to rearrange them.

1Rows and columns

A list of lists becomes a 2D array: a grid with rows and columns. .shape gives (rows, columns), .ndim the number of dimensions and .size the number of values.

import numpy as np

# 3 users (rows) by 4 weeks (columns) of sessions
sessions = np.array([[5, 3, 6, 2], [0, 1, 4, 4], [7, 8, 2, 5]])
print(sessions.shape, sessions.ndim, sessions.size)
sessions
NumPy (illustrative numbers)

Practice

scores has one row per student and one column per test. Store the number of students (rows).

import numpy as np

scores = np.array([[71, 80, 65], [90, 88, 94], [55, 62, 70], [84, 79, 91], [60, 75, 68]])
result = ...
NumPy (illustrative numbers)

2Reshape into a grid

reshape(rows, cols) lays the same values out in a new shape, row by row. The total number of values must stay the same.

import numpy as np

monthly = np.arange(1, 13) * 10
quarters = monthly.reshape(4, 3)
quarters
NumPy (illustrative numbers)

Practice

Store the numbers 1 to 12 arranged into 3 rows of 4.

import numpy as np

result = ...
NumPy (illustrative numbers)

3Let NumPy work it out with -1

Put -1 for one dimension and NumPy works out its size. reshape(-1) (or .flatten()) turns any grid back into one flat row of values.

import numpy as np

grid = np.arange(12).reshape(2, -1)
print(grid.shape)
print(grid.reshape(-1))
NumPy (illustrative numbers)

Practice

Flatten grid into a single 1D array, row by row.

import numpy as np

grid = np.array([[3, 1], [4, 1], [5, 9]])
result = ...
NumPy (illustrative numbers)

4Swap rows and columns with .T

.T (transpose) turns rows into columns. A users-by-weeks grid becomes a weeks-by-users grid.

import numpy as np

sessions = np.array([[5, 3, 6, 2], [0, 1, 4, 4], [7, 8, 2, 5]])
print(sessions.shape, sessions.T.shape)
sessions.T
NumPy (illustrative numbers)

Practice

sales has one row per store and one column per day. Store it the other way round: one row per day, one column per store.

import numpy as np

sales = np.array([[120, 95, 130], [80, 110, 70]])
result = ...
NumPy (illustrative numbers)