Performing Mathematical Operations
One of NumPy's major advantages is vectorization. Instead of writing a loop to process every value, you can apply an operation directly to an entire array.
Element-wise Arithmetic
import numpy as np
prices = np.array([100, 200, 300, 400])
discounted_prices = prices * 0.90
taxed_prices = prices * 1.18
print(discounted_prices)
print(taxed_prices)
Each operation is applied to every element in the array.
You can also perform calculations between arrays of compatible shapes.
units_sold = np.array([10, 20, 15, 25])
unit_prices = np.array([100, 150, 200, 120])
revenue = units_sold * unit_prices
print(revenue)
print("Total revenue:", np.sum(revenue))
The multiplication calculates revenue for each product, while np.sum() calculates the combined revenue.
Aggregation Functions
NumPy provides functions to calculate common statistical measurements.
sales = np.array([12000, 15000, 18000, 22000, 25000])
print("Total:", np.sum(sales))
print("Mean:", np.mean(sales))
print("Median:", np.median(sales))
print("Minimum:", np.min(sales))
print("Maximum:", np.max(sales))
print("Standard deviation:", np.std(sales))
These operations help summarize a dataset quickly. By default, np.std() calculates the population standard deviation (ddof=0). Use np.std(sales, ddof=1) when the sample standard deviation is required and the sample contains enough observations.
Python for Data Science
Vishalini A








