In [1]:
# - compatibility with Python 3
from __future__ import print_function  # print('me') instead of print 'me'
from __future__ import division  # 1/2 == 0.5, not 0
In [2]:
# - show figures inside the notebook
%matplotlib inline
In [3]:
# - import common modules
import numpy as np  # the Python array package
import matplotlib.pyplot as plt  # the Python plotting package

Reshaping with np.newaxis

We often want to reshape, adding a single axis length 1. For example, let's say we had a 1d array:

In [4]:
arr_1d = np.array([3, 2, 5])
arr_1d
Out[4]:
array([3, 2, 5])

We may want to make this into a 2D column vector array, with shape (3, 1). Obviously we could do that with reshape:

In [5]:
col_vector = arr_1d.reshape(3, 1)
col_vector
Out[5]:
array([[3],
       [2],
       [5]])

This need, of adding a single length 1 dimension, is so common, that numpy has a fancy way of doing that. To do this, you use the constant np.newaxis inside a slicing operation, to return the requested slice, but with an extra length 1 axis in the position you specified:

In [6]:
arr_1d[:, np.newaxis]  # Add length 1 axis to end, make column vector
Out[6]:
array([[3],
       [2],
       [5]])
In [7]:
arr_1d[np.newaxis, :]  # Add length 1 axis to start, make row vector
Out[7]:
array([[3, 2, 5]])