Ravindra BagaleCourses & study guides मराठी Track your progress

NumPy Tutorial for Beginners: Arrays, Maths and Filtering in Python

P12.3 NumPy Array Maths: Add, Multiply and Compare Whole Arrays

Why. Revenue = qty × price for every row. With arrays, you multiply two whole columns at once.

What. Operators work element by element: position 0 with 0, 1 with 1, and so on. The arrays must have the same length.

How.

Calculate a new column

  1. Make one array per column.
  2. Use normal operators between them.
  3. Store the result as a new array.
1. qty = [3, 2, 5]2. price = [56, 40, 84]3. Multiply position by position4. revenue = [168, 80, 420]
qty × price element by element (read from top to bottom)

Worked example A — Revenue per row.

Step 1 — What we do. Three sales at a store in Pune.

Step 2 — Type and run this code.

import numpy as np
qty = np.array([3, 2, 5])
price = np.array([56, 40, 84])
revenue = qty * price
print(revenue)
print(revenue.sum())

Step 3 — Output you should see.

[168  80 420]
668

Step 4 — What it means. Each position is multiplied with its partner. Total ₹668.

Worked example B — Currency conversion and rounding.

Step 1 — What we do. Convert pounds to euros at 1.17 and round.

Step 2 — Type and run this code.

import numpy as np
gbp = np.array([19.99, 45.50, 120.00])
eur = np.round(gbp * 1.17, 2)
print(eur)

Step 3 — Output you should see.

[ 23.39  53.24 140.4 ]

Step 4 — What it means. One line converts and rounds every value.

Worked example C — Percentage change.

Step 1 — What we do. Monthly users of an app, change from last month.

Step 2 — Type and run this code.

import numpy as np
users = np.array([1000, 1150, 1100, 1320])
change = (users[1:] - users[:-1]) / users[:-1] * 100
print(np.round(change, 1))

Step 3 — Output you should see.

[15.  -4.3 20. ]

Step 4 — What it means. Slicing gives "this month" and "last month" arrays. This is what pandas pct_change() does.

Ravindra Bagale's Tip

If you get "operands could not be broadcast together", your arrays have different lengths. Print .shape of each.