reshape pours, transpose moves
Both of these turn the two-student table, (2, 3), into a (3, 2) table. Only one keeps the meaning.
print(scores.T)
print(scores.reshape(3, 2))
[[ 70 50]
[ 80 100]
[ 90 60]]
[[ 70 80]
[ 90 50]
[100 60]]
scores.T is the transpose: each test is now a row, and each student is a column. Every number still belongs to its student and its test.
scores.reshape(3, 2) reads the numbers in order, 70, 80, 90, 50, 100, 60, and pours them into rows of two. Its second row is [90, 50]: Ana's test 3 next to Ben's test 1. That row means nothing.
Each number below wears its student's color. Switch between the two and watch the colors.
scores (2, 3)scores.T (3, 2)scoresscores.Tscores and number 3 in the result. Transpose moved it, and every number still belongs to its student and its test.- reshape reads the numbers in order and pours them into the new shape. The order never changes. Only the line breaks move.
- transpose moves numbers. What was a column is now a row.
So use reshape to split one axis into two, or to join two axes that sit next to each other. Joining the class axis and the student axis of classes puts every student in one table:
print(classes.reshape(-1, 3))
[[ 70 80 90]
[ 50 100 60]
[ 85 75 95]
[ 60 70 80]]
-1 means: work this size out for me. Four students in all, Ana, Ben, Dee and Eli, each with 3 tests. That join is safe, because class and student sit next to each other and stay in order.
When axes must change places, use a transpose. np.transpose(classes, (2, 0, 1)) lists the old axes in their new order: tests first, then classes, then students, so the shape becomes (3, 2, 2).
The classic bug is a reshape where a transpose belongs. The shape comes out right and the numbers are scrambled, like the [90, 50] row above.
In the editor, fill in everyone, all four students of classes in one (4, 3) table, and by_test, the same scores with one row per test and one column per student.