# Python NumPy For Your Grandma - 3.2 newaxis

Contents

In this section, we’ll see how to use the `newaxis` keyword to increase the dimensionality of an array and why that’s useful.

Suppose you have these two arrays, `A` and `B`, and your goal is to build a 4x3 difference matrix where element ij gives A_i - B_j. In other words, your goal is to subtract each element of `B` from each element of `A`.

``````import numpy as np

A = np.array([3, 11, 4, 5])
print(A)
## [ 3 11  4  5]
B = np.array([5, 0, 3])
print(B)
## [5 0 3]
``````

If you do `A` minus `B`, you’ll get an error because the arrays don’t have compatible shapes and even if they were the same size, numpy would just do element-wise subtraction which isn’t what we want.

However, imagine if `A` was a 4x1 array and `B` was 1x3 array. In this case, numpy would use broadcasting to, in essence, turn them both into 4x3 arrays, and then carry out the element-wise subtraction that we want. So the question is, how do we convert `A` into a 4x1 array and `B` into a 1x3 array?

Surprise, surprise - you can use `np.newaxis` for that. So if we do `A[:, np.newaxis]`, it inserts a new axis behind `A`’s existing axis. In other words, it converts `A` from a (4.) array into a (4,1) array.

``````A[:, np.newaxis]
## array([[ 3],
##        [11],
##        [ 4],
##        [ 5]])
``````

And then if we do `B[np.newaxis, :]`, it inserts a new axis in front of `B`’s existing axis. In other words, it converts `B` from a (3,) array into a (1,3) array.

``````B[np.newaxis, :]
## array([[5, 0, 3]])
``````

And now we can just carry out the subtraction to get our desired difference matrix.

``````A[:, np.newaxis] - B[np.newaxis, :]
## array([[-2,  3,  0],
##        [ 6, 11,  8],
##        [-1,  4,  1],
##        [ 0,  5,  2]])
``````

Note that `newaxis` is just an alias for the `None` keyword, so you’ll often see people, including myself, use the None keyword here.

``````A[:, None] - B[None, :]
## array([[-2,  3,  0],
##        [ 6, 11,  8],
##        [-1,  4,  1],
##        [ 0,  5,  2]])
``````