Python NumPy For Your Grandma | Section 3.2 | newaxis
- 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
- Intermediate Array Stuff
3.4 boolean indexing
- Common Operations
4.2 Math Funcs
4.3 all and any
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.