Thinking in Arrays: A NumPy Student Performance Analysis
A full NumPy use case: 50 students and 5 subjects, normalised with z-scores, ranked with argsort, graded with np.where and filtered with masks, written from a short prompt and checked line by line. Plus a weather challenge.
What you will learn
- Replace a row-by-row loop with one array expression and check they agree
- Ask the four array questions: shape, operations, vectorize, axis
- Normalise, rank, grade and filter 50 students with NumPy only
- Review AI-written NumPy code by checking each requirement against its output
Before you start
- NumPy aggregation and the axis parameter
- NumPy broadcasting
- NumPy random generators
You've met NumPy one tool at a time: arrays, shapes, broadcasting, the axis parameter. Now you'll use them together on a whole problem, a student performance analysis. The habit you're building is called thinking in arrays.
Think about a long sheet of exam marks where you need each student's average. One way is to take a calculator, add up the first row, write the answer, and move to the next row, again and again. That's a loop. The other way is to tell the whole sheet "average every row", and the answer column fills in one go. You describe the result for the whole table, instead of the steps for one row.
Loop or array
import numpy as np
rng = np.random.default_rng(42)
scores = rng.integers(40, 101, size=(50, 5))
result = []
for i in range(len(scores)):
row_avg = sum(scores[i]) / len(scores[i])
result.append(row_avg)
fast = scores.mean(axis=1)
print(np.round(result[:3], 1))
print(fast[:3].round(1))
print(np.allclose(result, fast))
[68.6 63.2 84.8]
[68.6 63.2 84.8]
True
Fifty students, five subjects, a fixed seed so the numbers stay the same. The loop repeats fifty times; the array version is one line, and allclose confirms all fifty answers agree. The array line is shorter, easier to read, and runs in compiled code. That's a hint for your prompts too: ask for vectorized code.
Four questions before you write anything
- What's the shape? A flat list, a table, or something with three dimensions.
- What operations do I need? Maths, totals, sorting or filtering.
- Can I vectorize it? Usually broadcasting or a ufunc can replace the loop.
- Which axis? Axis 0 gives one answer per column, axis 1 gives one per row.
The use case and its prompt
Fifty students, five subjects: analyse their performance using only NumPy, with no loops doing the maths. The prompt uses the four parts from prompting fundamentals:
- Role: a Python tutor who writes clear NumPy code.
- Context: a table of 50 students across 5 subjects, scores from 40 to 100, a fixed seed.
- Task: normalise, rank, grade and filter, using only NumPy.
- Format: one simple script that prints a short report.
Notice what's missing. You don't name every function or spell out every step. Start short, and add one line when something's missing. What comes back is one possible result, so go through it piece by piece and check it against what you asked for.
Check the data first
rng = np.random.default_rng(42)
scores = rng.integers(40, 101, size=(50, 5))
print(scores.shape)
print(scores[:3])
print(scores.min(), scores.max())
(50, 5)
[[45 87 79 66 66]
[92 45 82 52 45]
[72 99 84 86 83]]
40 100
The high limit of 101 isn't included, so scores stop at 100. Rows are students, columns are Math, Science, English, History and Art. Min and max meet the requirement. Check the data before you trust anything built on top of it.
Normalise with a z-score
To compare scores across subjects, use the z-score: each value minus the subject's mean, divided by the subject's standard deviation.
means = scores.mean(axis=0)
stds = scores.std(axis=0)
normed = (scores - means) / stds
print(means.round(1))
print(means.shape, scores.shape)
print(normed.shape)
print(normed[0].round(2))
print(np.allclose(normed.mean(axis=0), 0))
print(np.allclose(normed.std(axis=0), 1))
[71.2 68.7 67.6 70.5 73.9]
(5,) (50, 5)
(50, 5)
[-1.48 1.06 0.67 -0.32 -0.49]
True
True
Axis 0 gives one mean per subject, and broadcasting stretches those five means down all fifty rows. Student 0's 45 in Math is well below the Math mean, hence -1.48. The two checks confirm each subject now has mean 0 and standard deviation 1.
The axis mistake
This one is easy to make, and easy to miss when you read AI code. Say you want to subtract each student's own average from their row:
avgs = scores.mean(axis=1)
print(avgs.shape)
normed = scores - avgs
(50,)
Traceback (most recent call last):
File "S05L08_Practice\student_axis_mistake.py", line 8, in <module>
normed = scores - avgs
~~~~~~~^~~~~~
ValueError: operands could not be broadcast together with shapes (50,5) (50,)
Shapes line up from the right, so 5 meets 50. The fix is keepdims=True:
avgs = scores.mean(axis=1, keepdims=True)
print(avgs.shape)
centered = scores - avgs
print(centered.shape)
print(np.allclose(centered.mean(axis=1), 0))
(50, 1)
(50, 5)
True
Now the 1 stretches across the five subjects. When you see that error, print both shapes first. (The rule is in ufuncs and broadcasting.)
Rank, grade and filter
avgs = scores.mean(axis=1)
ranks = avgs.argsort()[::-1]
print(ranks[:5])
print(avgs[ranks[:5]].round(1))
[ 9 2 12 21 18]
[85.6 84.8 81.4 81.2 80.6]
argsort gives the positions that would sort the averages, smallest first, and [::-1] puts the best first. Those are row numbers. Row 2's 84.8 is the one you saw in the loop check, so the ranking holds up.
grades = np.where(avgs >= 90, "A",
np.where(avgs >= 80, "B",
np.where(avgs >= 70, "C",
np.where(avgs >= 60, "D", "F"))))
print(grades[:8])
letters, counts = np.unique(grades, return_counts=True)
print(dict(zip(letters.tolist(), counts.tolist())))
['D' 'D' 'B' 'C' 'C' 'C' 'D' 'C']
{'B': 5, 'C': 23, 'D': 19, 'F': 3}
Each np.where asks a question across the whole array, and the next one handles "otherwise". The counts add up to 50. There's no A at all, and that's correct, not a bug: the top average is 85.6.
at_risk = scores[avgs < 60]
honor = scores[avgs >= 90]
good = scores[avgs >= 75]
q75 = np.percentile(scores, 75, axis=0)
print(at_risk.shape, honor.shape, good.shape)
print(q75)
(3, 5) (0, 5) (11, 5)
[87.75 85.75 82. 82. 87. ]
A mask of fifty True/False values picks whole rows. The honor roll has shape (0, 5): no error, just no rows, which matches the grades. The 75th percentile per subject says three quarters of Math scores are at or below 87.75.
Read the report against the prompt
subjects = ["Math", "Science", "English",
"History", "Art"]
avgs = scores.mean(axis=1)
ranks = avgs.argsort()[::-1]
grades = np.where(avgs >= 90, "A",
np.where(avgs >= 80, "B",
np.where(avgs >= 70, "C",
np.where(avgs >= 60, "D", "F"))))
mean = scores.mean(axis=0)
std = scores.std(axis=0)
low = scores.min(axis=0)
high = scores.max(axis=0)
print("STUDENT PERFORMANCE REPORT")
for k, name in enumerate(subjects): # printing only
print(f"{name:8} mean={mean[k]:.1f} std={std[k]:.1f}"
f" min={low[k]} max={high[k]}")
print("Top 3 students:")
for n, s in enumerate(ranks[:3], 1): # printing only
print(f" #{n}: student {s} avg={avgs[s]:.1f}"
f" grade={grades[s]}")
print("At risk (avg < 60):", (avgs < 60).sum())
print("Honor roll (avg >= 90):", (avgs >= 90).sum())
STUDENT PERFORMANCE REPORT
Math mean=71.2 std=17.7 min=42 max=100
Science mean=68.7 std=17.3 min=42 max=99
English mean=67.6 std=16.9 min=41 max=99
History mean=70.5 std=14.2 min=40 max=99
Art mean=73.9 std=16.2 min=41 max=100
Top 3 students:
#1: student 9 avg=85.6 grade=B
#2: student 2 avg=84.8 grade=B
#3: student 12 avg=81.4 grade=B
At risk (avg < 60): 3
Honor roll (avg >= 90): 0
Now tick off the requirements. The Math mean matches the normalise step. The top three match the ranking, each with a B. At risk 3 and honor roll 0 match the filters. And the two for loops? They only print lines. Every calculation above them is array maths, so the "no loops doing the maths" rule holds.
That's how you review AI code: go through your requirements one at a time, and check each against what it printed. Checking AI-written Python code has more on this habit.
Challenge: a weather analyser
Four cities, ten days, so the shape is 4 by 10. You need the average per city and per day, every temperature in Fahrenheit, the days above 35 per city, and the cities ranked hottest to coolest. Design the shape first, then try it yourself or prompt an AI tool and read what it gives you.
Here's one possible result:
import numpy as np
rng = np.random.default_rng(7)
cities = np.array(["North", "South", "East", "West"])
temps = rng.integers(20, 41, size=(4, 10))
per_city = temps.mean(axis=1)
per_day = temps.mean(axis=0)
fahrenheit = temps * 9 / 5 + 32
heat = temps > 35
rank = per_city.argsort()[::-1]
print(per_city.round(1))
print(per_day.round(1))
print(fahrenheit[0])
print(heat.sum(axis=1))
print(cities[rank])
[32. 29.8 30.4 33.9]
[33.2 32. 32.5 30.8 33.2 33.5 33.2 30.5 25. 31.2]
[102.2 91.4 93.2 100.4 89.6 96.8 98.6 75.2 69.8 78.8]
[4 4 2 4]
['West' 'North' 'East' 'South']
West comes first, then North, East and South, which matches the city averages. The project also has a sales challenge (four items over twelve months, summed into quarters with reshape(4, 4, 3).sum(axis=2)) if you want a second one.
Recap
| Step | NumPy tool |
|---|---|
| Think in arrays | Shape first, then axis, vectorize wherever you can |
| Normalise | (scores - mean(axis=0)) / std(axis=0) |
| Per-row maths | keepdims=True so (50, 1) broadcasts |
| Rank | argsort()[::-1] |
| Grade | Nested np.where |
| Filter | scores[avgs < 60] |
| Review | Each requirement against each printed line |
Try it yourself: write your own prompt for this use case, with role, context, task and format, without copying this one. Run what you get, and check it the same way.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Supervised Learning: Features, Labels, Classification and Regression
What supervised learning is, shown on one small job: sorting support tickets into billing and technical. Rules vs learning from examples, classification vs regression, why some tickets stay hidden, and a 12-ticket classifier that labels three new ones.
NumPy and pandas for AI Engineers: Arrays for Vectors, Tables for Logs
NumPy and pandas at the depth an AI engineer needs. Shape, axis and broadcasting on 1,000 sample embeddings, a loop against one @, then a 2,000-row model call log: dtypes on load, missing values, filters, groupby model, merge and resample.
NumPy Arrays: Creation, Shape and Data Types From Scratch
Why a NumPy array beats a list for numbers, the seven ways to create one, what shape, ndim, size and dtype tell you, and why a slice is a view. Every output is from a real run on NumPy 2.
NumPy Indexing, Slicing, Masks and np.where
Get values out of a NumPy array by position, by range, by condition and by a list of positions, write through slices, use np.where three ways, and learn which picks are views and which are copies.
