P45NumPyIntermediateImplement10 min

Vectorize a Calculation Instead of Looping Row by Row

Use NumPy element-wise operations and boolean masks.

#numpy#arrays#vectorization#boolean masks

Scenario

Revenue and cost arrays must produce profit and identify rows above a 500 threshold.

Problem statement

Write or interpret a vectorized NumPy solution.

Your Task

  1. Calculate profit element-wise.
  2. Create a boolean mask.
  3. Explain compatible-shape assumptions.
  4. Explain readable vectorization.

Input

import numpy as np
revenue = np.array([1200, 800, 1500])
cost = np.array([500, 450, 700])

Related Concepts

NumPy arraysBroadcastingBoolean indexing

Ready to count this problem?

Mark it complete when you have reasoned through the solution in your own words.