Whole arrays at once
NumPy is the library almost all of Python's number crunching stands on – pandas from lesson 69 is built on it, and so are matplotlib and scikit-learn in the next two lessons. Its idea is simple: an array of numbers that you calculate with as a whole. No loop – NumPy runs the loop for you, in fast compiled code.
We reach it through pycall again. Here are five temperatures in Celsius, turned into Fahrenheit in one line:
require "pycall"
np = PyCall.import_module("numpy")
temps = np.array([12.5, 15.0, 9.5, 21.0, 18.5])
temps * 9 / 5 + 32np.array makes an array from a Ruby array. * 9 / 5 + 32 then works on every number at once. In plain Ruby that would be temps.map { |t| t * 9 / 5 + 32 } – the same result, but NumPy is much faster once there are millions of numbers.
An array also knows how to sum itself up. A single number comes back as a Ruby number:
puts temps.mean
puts temps.max
temps.argmaxmean is the average, max the largest value, and argmax where it is: at index 3, counting from 0. Picking values works like in pandas – a question for every element, a True/False array, and that array in square brackets:
temps[temps > 15]Only the warm days are left. To make arrays without typing them: np.arange counts like a Ruby range (the end is not included), and np.linspace spreads a number of points evenly between two values:
puts np.arange(1, 11) ** 2
np.linspace(0, 1, 5)** 2 squares all ten numbers at once.
Arrays can also have rows and columns, like a table or a chessboard. reshape(3, 4) folds 12 numbers into 3 rows of 4:
grid = np.arange(12).reshape(3, 4)
puts grid
puts "shape: #{grid.shape}"
grid.sum(axis: 0)shape says how big the array is: 3 rows, 4 columns. In Python that is a tuple, (3, 4); pycall turns it into a Ruby array. sum(axis: 0) adds up every column (axis 0 runs down the rows); axis: 1 would add up every row instead.
NumPy also brings random numbers. Let's throw a die 6000 times and count how often each face came up:
rng = np.random.default_rng(42)
dice = rng.integers(1, 7, size: 6000)
np.bincount(dice)default_rng(42) is a random-number generator; the 42 (the seed) makes it give the same numbers every time, so you can check the result. integers(1, 7, size: 6000) throws 6000 dice – 7 is not included. bincount counts how often each number appears, starting at 0: no zeros, and about 1000 of each face.
Back to Ruby, as with pandas: tolist makes a Python list, to_a a Ruby array.
temps.tolist.to_a.map { |t| t.round }From there on, Ruby's own methods work again – here map with round.
pip install numpy and gem install pycall, and the code of this lesson runs unchanged. For numbers in Ruby itself there is Numo::NArray, which works much like NumPy. NumPy comes under the BSD licence.
passed, as a Ruby number.require "pycall"
np = PyCall.import_module("numpy")
scores = np.array([55, 72, 61, 48, 90, 67, 59])
# passed = ... (how many scores are 60 or more)