Python NumPy For Your Grandma | Section 3.2 | newaxis


Course Contents

  1. Introduction
  2. NumPy Arrays
    2.1 What’s A NumPy Array
    2.2 Creating NumPy Arrays
    2.3 Indexing And Modifying 1-D Arrays
    2.4 Indexing And Modifying Multidimensional Arrays
    2.5 Basic Math
  3. Intermediate Array Stuff
    3.1 Broadcasting
    3.2 newaxis
    3.3 reshape
    3.4 boolean indexing
    3.5 nan
    3.6 infinity
    3.7 random
  4. Common Operations
    4.1 where
    4.2 Math Funcs
    4.3 all and any
    4.4 concatenate
    4.5 Stacking
    4.6 Sorting
    4.7 unique
  5. Challenges

This video covers the newaxis keyword for inserting a new axis into a numpy array to increase its dimensionality. newaxis is usually used to make arrays compatible for broadcasting.


import numpy as np

# make 1d arrays
A = np.array([3, 11, 4, 5])
B = np.array([5, 0, 3])

# Deduct each element of B from each element of A
A[np.newaxis, :] - B[:, np.newaxis]

# Same as above, using None
A[None, :] - B[:, None]


Sometimes you may want to increase the dimensionality of an array by giving it a new axis. For example, suppose you have the following 1d arrays.
If you wanted to deduct each element of B from each element of A, you’d need to make the arrays compatible for subtraction. If A was a 1x4 array and B was a 3x1 array, A minus B would broadcast to your desired result. Surprise: you can use np.newaxis to promote the dimensionality of A and B for tasks like these. To use it, just put np.newaxis in the square bracket notation where ever you want to add a new axis.
For example, “A square bracket new axis comma colon” inserts a new axis in front of A’s existing axis, turning A into a 1x4 array and “B colon comma new axis” inserts a new axis behind B’s existing axis, turning B into a 3x1 array.
Note that newaxis is just an alias for the keyword None, so you’ll often see people using the None keyword here.