Data Science
NumPy foundations: arrays, shapes and indexing
Move from a Python list to a typed array, inspect shape and select rows with slices and boolean masks.
What you will learn
Move from a Python list to a typed array, inspect shape and select rows with slices and boolean masks.
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
An ndarray stores one dtype across its elements. shape describes axis lengths; ndim counts axes; size counts elements. Indexing starts at zero and slice stops are exclusive. Boolean masks must align with the axis being selected. A basic slice can share memory with its source, so use copy() before a change you want to keep isolated. Vectorisation removes Python-loop overhead but does not make every operation a single CPU instruction.
Follow a worked example
a = np.array([2, 5, 1, 2], dtype=np.int64)
print(a.shape, a.ndim, a.size)
print(a[a >= 2])
Expected result
(4,) 1 4, followed by [2 5 2].
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: Build an array from all sales unit counts.
Success criteria: Shape (12,), ndim 1, sum 37.
Need a starting point? Show the hint
Select the units Series and call to_numpy().
Reference solution — open after trying
units = df['units'].to_numpy()
print(units.shape, units.ndim, units.sum())
Medium: Select orders with five or more units using a boolean mask.
Success criteria: [5, 10, 5], sum 20.
Need a starting point? Show the hint
Reuse the same units array; compare it with 5.
Reference solution — open after trying
units = df['units'].to_numpy()
print(units[units >= 5])
assert units[units >= 5].sum() == 20
Hard: Create a 3×4 monthly units matrix.
Success criteria: Row sums [10,15,12]; grand total 37. Reconcile the matrix with the original Series.
Need a starting point? Show the hint
Reshape the 12 ordered values to (3,4), then sum axis=1.
Reference solution — open after trying
matrix = df['units'].to_numpy().reshape(3,4)
print(matrix.sum(axis=1))
assert matrix.sum(axis=1).tolist() == [10,15,12]
assert matrix.sum() == 37
Professional: Prove a derived array cannot accidentally mutate the source.
Success criteria: The edited copy begins with 999; the original units still begins with 2. Document copy versus view.
Need a starting point? Show the hint
Use .copy() when extracting the first three elements.
Reference solution — open after trying
units = df['units'].to_numpy(copy=True)
preview = units[:3].copy()
preview[0] = 999
assert units[0] == 2
print(preview, units[:3])
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.
a = np.array([2, 5, 1, 2], dtype=np.int64)
print(a.shape, a.ndim, a.size)
print(a[a >= 2])Lesson Code (python)
a = np.array([2, 5, 1, 2], dtype=np.int64)
print(a.shape, a.ndim, a.size)
print(a[a >= 2])Console Output
(4,) 1 4, followed by [2 5 2].Up next · Continue learning
broadcasting, statistics and safe division
Calculate revenue, weighted prices and normalized features with explicit axis and zero-division checks.