Chaining NumPy Operations
Introduction
Welcome back to Vectorized Operations. We’re on Lesson 4 of 5, and so far, we’ve used arithmetic operators on arrays one operation at a time. Now we’ll chain operations into a single expression. We’ll start with a temperature conversion loop, then see how operator order and parentheses affect array calculations. By the end, we’ll combine two arrays and a number in one formula.
From a Loop to One Line
When a loop applies the same calculation to each value, we can often express that calculation directly on an array. NumPy applies arithmetic element by element, so we don’t need to build a result list with append(). As always, we import NumPy as np first; the later snippets in this lesson use the same import.
The loop calculates and appends one Fahrenheit value at a time. The array expression performs the same calculation on every value in celsius and prints the result without a loop. As you may recall from earlier lessons, / produces floating-point results.
The values match, although Python displays the list and NumPy array differently. NumPy arithmetic applies element by element and returns a new array.
Operator Precedence Applies to Arrays Too
An array expression follows the same arithmetic order as an expression with plain numbers. Exponents are evaluated before multiplication and division, which come before addition and subtraction. In celsius * 9 / 5 + 32, multiplication and division are evaluated from left to right, and then 32 is added to each result. That order matches the Fahrenheit formula: multiply Celsius by 9, divide by 5, and then add 32.
The parentheses make the conversion steps easy to see. Here, they do not change the result because multiplication and division already happen before addition. Printing fahrenheit shows the same values as the array expression in the previous section:
Python’s usual precedence rules apply to NumPy expressions, too.
