Math on Whole Arrays
Part of the Data and Plots section of Coddy's Machine Learning journey. Lesson 10 of 60.
A shop sold 3, 1 and 2 of its three items. A list would need a loop to find what each earned. An array pairs the values up:
In code:
prices = np.array([4, 10, 25])
sold = np.array([3, 1, 2])
print(prices * sold)
print(prices * 2)This prints:
[12 10 50]
[ 8 20 50]A single number reaches every value: prices * 2 doubles them all. This is element-wise math: no loop, no index.
The same goes for +, -, / and **. Division always gives decimals.
By this chapter's end, lines like these will grade a whole class.
Challenge
EasyA runner logged three runs. The program reads their distances into km and their times into minutes. Without a loop:
- Make
meters: every distance in meters (1 km is 1000 m). - Make
pace: each run's minutes per kilometer, its time divided by its distance. - Print both after their labels, as below.
For runs of 5, 10 and 4 km that took 30, 55 and 26 minutes:
Meters: [ 5000 10000 4000]
Minutes per km: [6. 5.5 6.5]Try it yourself
import numpy as np
km = np.array([int(input()), int(input()), int(input())])
minutes = np.array([int(input()), int(input()), 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 Grid3Array Math
Math on Whole ArraysSummary StatisticsStatistics by AxisBroadcastingBoolean MasksRecap: Exam Scores9Grouping and Cleaning
Counting ValuesGrouping DataSeveral SummariesMissing ValuesRecap: Survey ResultsPractice on your own: Online Python compiler