Data Science
NumPy applied: broadcasting, statistics and safe division
Calculate revenue, weighted prices and normalized features with explicit axis and zero-division checks.
What you will learn
Calculate revenue, weighted prices and normalized features with explicit axis and zero-division checks.
Before you start
You need basic variables, lists and function calls, not advanced Python algorithms. If these are new, visit Python foundations first.
- Create a local environment:
python -m venv .venv. Activate it for your OS and installpython -m pip install jupyterlab numpy pandas matplotlib seaborn plotly. - Download the 12-row sales CSV into your notebook folder. Keep its filename unchanged.
- Start Jupyter with
jupyter lab. Run the setup below in a fresh notebook before every workshop.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import plotly.express as px
raw = pd.read_csv('data-science-sales.csv', parse_dates=['date'])
df = raw.copy()
df['revenue'] = df['units'] * df['unit_price']
net = df.loc[df['returned'].eq(0)].copy()
Data dictionary: each row is one order for one product; units is a positive count; unit_price is INR per unit; returned is 0 or 1. Revenue is units × unit_price. For this workshop, net sales exclude the entire returned order (not partial returns). The CSV has 12 rows, 4950 gross revenue, 4450 net revenue and 35 net units. This small fictional sample teaches technique; it does not justify population or causal claims.
Save your notebook and written interpretation. There is no browser code judge and no automatic grading of visual design.
Learn the idea
Broadcasting compares shapes from the trailing axis: dimensions must match or one must be 1. Multiply aligned units and prices elementwise, not with a dot product unless you want a scalar. A simple average of product prices ignores quantities; weighted average selling price is revenue divided by units. Standardisation divides by a feature's standard deviation; constant features need a zero guard. Check vectorised results with a small hand calculation.
Follow a worked example
units = net['units'].to_numpy()
prices = net['unit_price'].to_numpy()
revenue = units * prices
print(revenue.sum())
Expected result
- All examples use non-returned rows.
Skill-development workshop
These are practical assignments, not MCQs or code-judge puzzles. Work in your own notebook or MySQL client. Complete the levels in order; if a task feels difficult, follow the hint and compare with the reference only after making an attempt. Keep your result and a short explanation of what it means.
Easy: Calculate a 10% revenue reduction without a loop.
Success criteria: 4005 total, using net sales only.
Need a starting point? Show the hint
Multiply each element by 0.9.
Reference solution — open after trying
revenue = net['units'].to_numpy() * net['unit_price'].to_numpy()
assert np.isclose((revenue * 0.9).sum(),4005)
Medium: Evaluate 5%, 10% and 15% discounts in one matrix.
Success criteria: Shape (11,3); totals [4227.5,4005,3782.5].
Need a starting point? Show the hint
Reshape revenue to a column with [:,None].
Reference solution — open after trying
revenue = net['revenue'].to_numpy()
scenarios = revenue[:,None] * (1-np.array([0.05,0.10,0.15]))
print(scenarios.shape, scenarios.sum(axis=0))
Hard: Compute the quantity-weighted selling price.
Success criteria: Net revenue divided by net units; reconcile both denominators to the data rather than averaging price rows.
Need a starting point? Show the hint
np.average accepts weights; use units.
Reference solution — open after trying
weighted = np.average(net['unit_price'], weights=net['units'])
assert np.isclose(weighted, net['revenue'].sum()/net['units'].sum())
print(weighted)
Professional: Standardise units and prices without NaNs for constant columns.
Success criteria: Shape (11,2), both means approximately 0 and std 1 (ddof=0). Explain ddof and avoid an unmeasured speed claim.
Need a starting point? Show the hint
np.divide with out and where guards zero standard deviations.
Reference solution — open after trying
x=net[['units','unit_price']].to_numpy(dtype=float)
mean=x.mean(axis=0); std=x.std(axis=0)
z=np.divide(x-mean,std,out=np.zeros_like(x),where=std!=0)
assert np.allclose(z.mean(axis=0),0)
assert np.allclose(z.std(axis=0),1)
Reflection and submission
Save your queries/notebook and outputs. Write three sentences: what you changed, how you checked it, and one limitation. A correct chart or query without a clear interpretation is not a completed professional assignment.
units = net['units'].to_numpy()
prices = net['unit_price'].to_numpy()
revenue = units * prices
print(revenue.sum())Lesson Code (python)
units = net['units'].to_numpy()
prices = net['unit_price'].to_numpy()
revenue = units * prices
print(revenue.sum())Console Output
4450. All examples use non-returned rows.Up next · Continue learning
loading, selecting and validating data
Read a CSV, inspect types, select rows and repair a controlled dirty copy without silently changing the original.