# - 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
# - show figures inside the notebook
%matplotlib inline
# - import common modules
import numpy as np # the Python array package
import matplotlib.pyplot as plt # the Python plotting package
np.newaxis¶We often want to reshape, adding a single axis length 1. For example, let's say we had a 1d array:
arr_1d = np.array([3, 2, 5])
arr_1d
We may want to make this into a 2D column vector array, with shape (3, 1). Obviously we could do that with reshape:
col_vector = arr_1d.reshape(3, 1)
col_vector
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:
arr_1d[:, np.newaxis] # Add length 1 axis to end, make column vector
arr_1d[np.newaxis, :] # Add length 1 axis to start, make row vector