{:title ["Transposing and Axes Reordering"]}
import numpy as np
Q: How many indices do we need to address a single entry in a ndarray?
A: The number of axes the ndarray has.
# 2D matrix has 2 axes
M = np.array([[1,2,3],
[4,5,6]])
M[0,1]
# Listing the sizes of each axes
M.shape
# Explicitly counting the number of axes of M
len(M.shape)
# Vector has 1 axes
v = np.array([1,2,3])
v[1]
v.shape
len(v.shape)
# Scalars have 0 axes
x = np.array(3.14)
x
x.shape
len(x.shape)
Transpose is an operation in linear algebra. It makes the rows of input matrix into columns of the output matrix.
# Here is the input matrix
M
# A quick way to obtain the transpose of M
M.T
#
# M.T is a special case of more general multi-axes transpose.
#
np.transpose(M, (1, 0))
#
# Transpose is also a method of the ndarray object
#
M.transpose((1,0))
We can change the shape of NDarrays as long as the total number of entries remain the same.
A ndarray with shape (4,3) has 12 elements. It can be reshaped into one (2,2,3)
+---+---+---+ +-------------------------------------+
| | | | | |
+---+---+---+ | +---+---+---+ +---+---+---+ |
| | | | ==> | |. |. |. | |. |. |. | |
+---+---+---+ | +---+---+---+ +---+---+---+ |
| | | | | |. |. |. | |. |. |. | |
+---+---+---+ | +---+---+---+ +---+---+---+ |
| | | | | |
+---+---+---+ +-------------------------------------+
It's easier to see how ndarrays are reshaped into vectors.
M
#
# Reshape always iterates over the __inner__ axes first,
# and then __outter__ axes.
#
np.reshape(M, (6,))
#
# This is what numpy is doing (fast)
#
I,J = M.shape
for i in range(I):
for j in range(J):
print(M[i,j])
#
# We can also use the reshape method
#
M.reshape((6,))
The reverse happens when converting a vector to a multi-axes ndarray.
v = np.array([1,2,3,4,5,6,7,8])
v
v.reshape((2,4))
A good way of understanding how reshape works is to imagine that the input ndarray is converted to a vector, which in turn is converted to the output ndarray.
A = np.array([[[1,2],
[3,4]],
[[5,6],
[7,8]]])
A
A.shape
B = A.reshape(2,4)
B
Transposing and reshaping are not the same. They may change the shape of a ndarray in the same way, but:
M
M.transpose(1,0)
M.reshape(3, 2)