Menu
CoddyTech

Reshaping Arrays

Part of the Data and Plots section of Coddy's Machine Learning journey. Lesson 16 of 60.

A shop's 12 monthly sales arrive as one flat array. Fold them into 4 quarters of 3 months, and new questions open up:

A strip of 12 monthly sales, 5 8 6 9 12 10 14 15 11 7 6 9, folds into a grid of 4 rows labelled Q1 to Q4, three months per row, in the same order

.reshape(rows, columns) fills the rows in order:

months = np.array([5, 8, 6, 9, 12, 10, 14, 15, 11, 7, 6, 9])
quarters = months.reshape(4, 3)
print(quarters.sum(axis=1))
print(months.reshape(2, -1).shape)

This prints:

[19 31 40 22]
(2, 6)

The sizes must multiply to the count: 4 times 3 is 12. Write -1 for one size and NumPy works it out.

.flatten() turns any table back into one flat array. This chapter ends with a dice game folded into rounds the same way.

challenge icon

Challenge

Easy

A reader logged their reading minutes for 3 weeks, Monday to Sunday, in the flat array minutes. The program reads a week number: 1, 2 or 3.

  1. Reshape minutes into weeks, one row per week.
  2. Print Weeks:, then the table.
  3. Print each week's total.
  4. Print the chosen week's row.

For a 2-week log and the input 2:

Weeks:
[[10  0 25 30 15 45 20]
 [ 5 35 40  0 20 60 30]]
Weekly totals: [145 190]
Week 2: [ 5 35 40  0 20 60 30]

Try it yourself

import numpy as np

# Minutes read each day for 3 weeks, Monday to Sunday
minutes = np.array([20, 35, 15, 0, 40, 60, 45, 25, 30, 20, 10, 35, 50, 55,
                    30, 30, 25, 20, 45, 40, 70])
week = int(input())

# Write your code below
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Data and Plots

Practice on your own: Online Python compiler