Notes on Numpy

Heiegg

2023-04-03

Numpy: axes of ndarray

Let k be a positive integer. Let A be an ndarray of shape (m_{0},\ldots , m_{k-1}) where m_{s}’s are positive integers for s=0,\ldots, k-1. There are k axes: axis 0, axis 1,\ldots, axis k-1. The length of axis s is m_{s}. An entry in A can be indexed as A[i_{0},\ldots, i_{k-1}], with 0\le i_{s} \le m_{s} - 1 for s=0,\ldots, k-1. Fix s^{\circ} and let i_{s^{\circ}} vary while all other i_{s} are fixed. Then we get a slice of A along the axis s^{\circ}.

Let w be an element in the permutation group S_{k}. It can be viewed as a function w: \left\{ 0,\ldots, k-1 \right\} \rightarrow \left\{ 0,\ldots, k-1 \right\}. Then the axis-moving functions, moveaxis, rollaxis, transpose, etc. can all be represented by an element w\in S_{k}. Axis s is moved to axis w(s). An axis-moving function then returns the ndarray B of shape (m_{w^{-1}(0)}, \ldots , m_{w^{-1}(k-1)}) such that B[i_{w^{-1}(0)},\ldots , i_{w^{-1}(k-1)}] = A[i_{0},\ldots , i_{k-1}] \quad\text{for $0\le i_{s}\le m_{s}$} or B[i_{0},\ldots , i_{k-1}] = A[i_{w(0)},\ldots , i_{w(k-1)}] \quad\text{for $0\le i_{s}\le m_{w^{-1}(s)}$}.

numpy.newaxis is an alias of None. When referencing an entry, the \mathrm{None} indices will be skipped over. For example, we have A[i_{0},\ldots, i_{a}, \mathrm{None}, i_{a+1} ,\ldots, i_{k-1}] = A[i_{0},\ldots, i_{a}, i_{a+1} ,\ldots, i_{k-1}]. We can use this to increase the number of axes by 1. For example, A[:,\ldots, :, \mathrm{None}, : ,\ldots, :] is an ndarray B of shape (m_{0},\ldots, m_{a}, 1, m_{a+1} ,\ldots, m_{k-1}) such that B[i_{0},\ldots, i_{a}, 0, i_{a+1} ,\ldots, i_{k-1}] = A[i_{0},\ldots, i_{a}, i_{a+1} ,\ldots, i_{k-1}].