I’m trying to understand what np.newaxis does in NumPy and when it’s useful.
For example, applying it to a 1D array changes its shape from [0, 1, 2, 3] to either a row or column vector.
Can someone explain how np.newaxis works and when to use it for reshaping or broadcasting?
Looking for practical use cases involving np.newaxis.
@Punamhans For me, np.newaxis is super helpful when I want to make two arrays compatible for broadcasting.
Like, say I have a column vector and I want to add it to a row vector:
python
Copy
Edit
a = np.array([1, 2, 3])[:, np.newaxis] # shape (3, 1)
b = np.array([10, 20, 30]) # shape (3,)
Now I can broadcast a + b.T easily.
Without np.newaxis, I’d have to reshape manually, which feels less readable.
I mostly use np.newaxis to reshape a 1D array depending on whether I want a row or column:
python
Copy
Edit
arr = np.array([0, 1, 2, 3])
row = arr[np.newaxis, :] # shape (1, 4)
col = arr[:, np.newaxis] # shape (4, 1)
This is useful in plotting with matplotlib or passing data into ML models that expect a specific shape.
It’s basically just a shortcut for reshape() but more intuitive for me.
I use np.newaxis a lot when preparing single samples for models that expect 2D or 3D inputs.
For example:
python
Copy
Edit
image = np.array([28, 28]) # say a grayscale image
image = image[np.newaxis, ...] # now shape is (1, 28, 28)
That “batch dimension” is essential when feeding data into neural nets.
I like newaxis because it makes the intent obvious, you’re inserting a dimension, not just reshaping blindly.