liveBook · Manning

Transposition

As explained in Fast Python: High performance techniques for large datasets

Transposition is an operation that exchanges a matrix’s rows and columns or, more generally, reorders the axes of a tensor without changing its values.

A transposed NumPy array presents matrix axes in a different order without necessarily copying the data. The resulting view shares memory with the original; its strides describe how many bytes to move along each axis to find the next element. section 4.1.2

Because transposition is a fast view operation, it can also help align dimensions for broadcasting. For example, transpose a matrix, add a vector whose length matches the original row count, then transpose the result back to apply the vector row by row. section 4.2.2

m2x5 = linear.reshape((2, 5))
print(np.shares_memory(linear, m2x5))
 
print("2x5", m2x5.shape)
print("2x5 corners", m2x5[0, 0], m2x5[0, 4],
      m2x5[2, 0], m2x5[2, 4])
 
m5x2 = m2x5.T
print(np.shares_memory(m2x5, m5x2))
print("5x2", m5x2.shape)
print("5x2 corners", m5x2[0, 0], m5x2[0, 1],
      m5x2[4, 0], m5x2[4, 1])

Inspect how reshaping and `.T` change array shapes while `np.shares_memory` checks whether the arrays share storage. section 4.1.2

Shape can affect runtime

A reported Game of Life benchmark took 44 seconds for a 400 × 900,000 map over four generations, versus 20 seconds for its transposed 900,000 × 400 shape on the same computer. The cause is deferred, and results may differ across computers. section 5.6.2

How Fast Python: High performance techniques for large datasets covers it

How deep it goes
Explains shapes, shared memory, and strides, while deferring allocation details and the cause of shape-dependent timings.
Examples
Uses 2 × 5 and 5 × 2 shared-memory views, row-wise vector broadcasting, and differently shaped Game of Life maps.
What you can do after
Apply it via NumPy’s `.T` to create a shared-memory matrix view or align dimensions for row-wise broadcasting.
How it connects
Connects transposition to NumPy views, strides, and broadcasting.

Also explained in

Compare how 6 books explain transposition →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Fast Python: High performance techniques for large datasets. The section links point to the parts of the book it draws on.