90

I saw this example in the SciPy documentation:

x, y = np.random.multivariate_normal(mean, cov, 5000).T

What does the final .T actually do here?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Leon palafox
  • 2,675
  • 6
  • 27
  • 35
  • 11
    The secret to googling for this is to put it in quotes. Of course, when I googled for it I got this page! – Kallaste Apr 30 '17 at 08:37
  • I hope this helps someone else who comes across it, but, `.T` _reverses_ the order of the axes, instead of switching the last two. This means if your array `x` is 3-D, `x.T` is the same as `x.transpose((2, 1, 0))`. If you want to switch the last two axes, in this case, you would do `x.transpose((0, 2, 1))`. – Hameer Abbasi Feb 02 '18 at 07:39

3 Answers3

96

The .T accesses the attribute T of the object, which happens to be a NumPy array. The T attribute is the transpose of the array, see the documentation.

Apparently you are creating random coordinates in the plane. The output of multivariate_normal() might look like this:

>>> np.random.multivariate_normal([0, 0], [[1, 0], [0, 1]], 5)  
array([[ 0.59589335,  0.97741328],
       [-0.58597307,  0.56733234],
       [-0.69164572,  0.17840394],
       [-0.24992978, -2.57494471],
       [ 0.38896689,  0.82221377]])

The transpose of this matrix is:

array([[ 0.59589335, -0.58597307, -0.69164572, -0.24992978,  0.38896689],
       [ 0.97741328,  0.56733234,  0.17840394, -2.57494471,  0.82221377]])

which can be conveniently separated in x and y parts by sequence unpacking.

River
  • 8,585
  • 14
  • 54
  • 67
Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
  • I wonder how the .T attribute is updated ... is the result of transpose(self) stored in self.T whenever something is changed in the array? I suppose not, but I don't know how I could implement such an attribute, to be computed on demand only. – Max Oct 13 '21 at 04:23
  • 1
    @Max `T` is a [descriptor](https://docs.python.org/3/howto/descriptor.html). You can think of it as basically a function that is called whenever you access `.T`. Also note that the transpose is just a view into the same data as the original array, just with different strides. So if you do `b = a.T` and then change items in `a`, the corresponding items in `b` will also change. – Sven Marnach Oct 14 '21 at 21:20
13

.T is just np.transpose(). Best of luck

  • 2
    This is not the full picture. If the matrix has less than 2 dimensions it returns the original. So it is the transpose function with a form of runtime safety. – IsakBosman Mar 23 '20 at 00:08
2

Example

import numpy as np
a = [[1, 2, 3]]
b = np.array(a).T  # ndarray.T The transposed array. [[1,2,3]] -> [[1][2][3]]
print("a=", a, "\nb=", b)
for i in range(3):
    print(" a=", a[0][i])  # prints  1 2 3
for i in range(3):
    print(" b=", b[i][0])  # prints  1 2 3 
vk3who
  • 349
  • 2
  • 7