Permute/transpose xarray, Numpy, Matlab arrays
Permuting and transposing array dimensions are a common operation used in data analysis. Ideally these operations would be done with index tricks instead of copying arrays. In Matlab, these operations copy the array (slow, expensive). In Python, these operations are O(1) an index manipulation creating a new view into an array (fast).
In Matlab, transpose and permute are distinct methods. In Matlab, transpose() is strictly for 2-D matrices, while permute() is for reordering dimensions of N-D arrays.
In Python, xarray and Numpy arrays are popular.
Both use the .transpose()
method for N-D array dimension reordering–there is no separate “permute” method.
However, the syntax is distinct between xarray and Numpy.
xarray.Dataset
and
xarray.DataArray
have a .transpose(*dims)
method.
Note the “*” used to expand the arguments in the top line, which is equivalent to the bottom line.
# A.dims == ('x', 'y', 'z')
B = A.transpose(*('z', 'y', 'x'))
# this is equivalent
B = A.transpose('z', 'y', 'x')
# B.dims == ('z', 'y', 'x')
Numpy transpose can also permute by specifying a tuple of the desired order. For 2-D arrays, transpose by omitting the axes order argument.
B = A.transpose((2,1,0))
D = C.transpose()