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:
.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
EasyA 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.
- Reshape
minutesintoweeks, one row per week. - Print
Weeks:, then the table. - Print each week's total.
- 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
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Data and Plots
2NumPy Arrays
Creating ArraysShape and SizeRanges of NumbersIndexing and SlicingRecap: Temperature GridPractice on your own: Online Python compiler