NumPy Arrays and Vectorization
Explore how to manipulate NumPy arrays and use vectorization to replace loops with concise elementwise operations. Understand broadcasting rules for aligning different array shapes and create repeatable simulated data samples. This lesson helps you efficiently perform numeric calculations and prepare for working with labeled data in pandas.
A pharmacy has four orders with quantities qty = [1, 2, 1, 3] and unit prices price = [12.50, 4.00, 7.25, 3.10]. A loop can multiply each quantity by its matching price, but the calculation becomes harder to inspect as more columns and rules appear. NumPy lets us express the four order totals as one operation.
A NumPy array is an ordered grid of numbers stored with one shared dtype, or data type. For example, qty contains whole numbers while price contains decimal numbers. Unlike Python lists, NumPy arrays apply arithmetic elementwise, meaning each position combines with the matching position in the other array. Arrays with the same length can therefore multiply order by order.
Lines 5–6: The code creates
qtyandpriceas one-dimensional arrays with four elements each.Line 8: Because
qtyandprice...