Python, from Zero, for AILesson 71 of 89

Module 8 · Numbers in bulk: NumPy, pandas and the vector under every model

Shapes, axes and broadcasting: the wrong-shape bug that runs without complaint

In this lesson

  • 9 min read
  • 8 reading sections
  • Knowledge check
  • Lesson 2 of 10 in this chapter

This chapter’s goalLoad a messy CSV into pandas, clean its missing values and types, group and join it into the table a question needs, convert it to a NumPy array of the right shape and dtype, compute cosine similarity between one vector and a hundred thousand in a single vectorised expression, plot the result to a file, and explain from memory layout why the array version runs a hundred times faster than the loop it replaced.

This chapter’s media

The film explains chapter ideas. The audiobook narrates the complete teaching text.

FormatEnglishहिंदी
Chapter filmWatch1:43Not available
Full audiobookNot availableNot available

A little at a time

Explore an idea, try it, then check what stays.

Step 1 of 10Free · no account needed
Lesson steps

Shape is the first thing to check

Python
m = np.arange(12).reshape(3, 4)
m.shape       # (3, 4): 3 rows, 4 columns

A shape is a tuple with one number per dimension. (3, 4) is three rows of four. (4,) is a flat vector of four. (1, 4) is a row vector (a matrix with one row) and (4, 1) is a column vector. These four shapes hold nearly the same numbers and behave differently in every operation, and a large share of NumPy bugs are one of them standing where another was expected.

reshape reinterprets the same data:

Python
v = np.arange(6)
v.reshape(2, 3)        # 2 rows of 3
v.reshape(3, -1)       # -1 means "work it out": (3, 2)
v.reshape(-1, 1)       # column vector, (6, 1)
v[np.newaxis, :]       # row vector, (1, 6), without reshape

Your place and first choices stay on this browser. Classroom credit is recorded separately.

Stuck on something?Ask Divya, your AI tutor

How to cite: Addaly (2026) ‘Shapes, axes and broadcasting: the wrong-shape bug that runs without complaint’, in Python, from Zero, for AI. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/python-for-ai/shapes-and-broadcasting (Accessed: 21 November 2026).