2

In NumPy, you can transpose a ndarray with the transpose() method, but it has an attribute, T, as well.

When a ndarray is altered, not only the return value of transpose() method, but also the attribute T is automatically updated at the same time.

ndarray.transpose() is a function, so it is not to be wondered at.

However, T is not a function, but a mere attribute, so it must be updated before accessed.

  1. Do all the NumPy functions and methods update the T attribute every time they are called?

  2. If so, why? It is likely that, when handling huge matrices, computational cost of every operation would be very large even if it is not relevant to transposition. Isn't it more reasonable to call transpose() only when necessary instead of rewriting the T attribute every time?

This is a simple example:

>>> import numpy as np
>>> x = np.array([[1, 2, 3],
...               [4, 5, 6]])
...
>>> x
array([[1, 2, 3],
       [4, 5, 6]])
>>> x.T
array([[1, 4],
       [2, 5],
       [3, 6]])

Of course, operation on x simultaneously changes x.T as well. When was x.T updated? Did x.__imul__() do it?

>>> x *= 100
>>> x
array([[100, 200, 300],
       [400, 500, 600]])
>>> x.T
array([[100, 400],
       [200, 500],
       [300, 600]])
2
  • 4
    ndarray.T is simply a view into ndarray.
    – Divakar
    Sep 23, 2020 at 15:14
  • np.transpose delegates the task to the x.transpose() method. x.T is a property, a shorthand means of calling that method. So nothing is calculated or stored ahead of time. But returning the transpose is (relatively) fast - it is a new array, with its own shape and strides, but sharing the original data (view). So there's no copying.
    – hpaulj
    Sep 23, 2020 at 16:58

1 Answer 1

1

The T property which is the same as .transpose() is just a view with the shape (and strides) changed. The memory of the actual content is the same (you can use a id(x[0,0]) and id(x.T[0,0]) for example to verify this), but the object properties tells NumPy how to interpret it.

For a 2D array, the strides and shape are just the reverse of the original array. To read more about strides see the documentation. This is why things are immediate when content changes - the memory cell gets the new number, but the interpretation of the .T array does not change.

Not the answer you're looking for? Browse other questions tagged or ask your own question.