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
- Make one array per column.
- Use normal operators between them.
- Store the result as a new array.
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.
Ravindra Bagale's Tip – मराठी
"operands could not be broadcast together" आलं तर तुमच्या arrays ची लांबी वेगळी आहे. प्रत्येकाचा .shape print करा.
Ravindra Bagale's Tip – हिंदी
"operands could not be broadcast together" आए तो आपकी arrays की लंबाई अलग है. हर एक का .shape print करो.