0
0
NumPydata~5 mins

np.newaxis for adding dimensions in NumPy

Choose your learning style9 modes available
Introduction

We use np.newaxis to add a new dimension to an array. This helps when we want to change the shape of data to fit certain operations.

When you want to convert a 1D list of numbers into a 2D column or row for math operations.
When preparing data to feed into machine learning models that expect specific input shapes.
When you need to align arrays with different dimensions for element-wise operations.
When reshaping data for broadcasting in calculations.
When adding a batch or channel dimension to image data.
Syntax
NumPy
array[:, np.newaxis]
array[np.newaxis, :]
# Insert new axis at desired position

np.newaxis is the same as None in indexing.

It does not copy data, just changes the view shape.

Examples
Adds a new axis to make a column vector with shape (3, 1).
NumPy
import numpy as np
arr = np.array([1, 2, 3])
arr_col = arr[:, np.newaxis]
print(arr_col.shape)
Adds a new axis to make a row vector with shape (1, 3).
NumPy
import numpy as np
arr = np.array([1, 2, 3])
arr_row = arr[np.newaxis, :]
print(arr_row.shape)
Adds a new axis at the end, changing shape from (2, 2) to (2, 2, 1).
NumPy
import numpy as np
arr = np.array([[1, 2], [3, 4]])
arr_expanded = arr[:, :, np.newaxis]
print(arr_expanded.shape)
Sample Program

This program shows how to add a new dimension to a 1D array to make it a column or row vector using np.newaxis. It prints the shapes and arrays to see the difference.

NumPy
import numpy as np

# Original 1D array
arr = np.array([10, 20, 30])
print('Original shape:', arr.shape)

# Add new axis to make it a column vector
arr_col = arr[:, np.newaxis]
print('Column vector shape:', arr_col.shape)
print('Column vector array:\n', arr_col)

# Add new axis to make it a row vector
arr_row = arr[np.newaxis, :]
print('Row vector shape:', arr_row.shape)
print('Row vector array:\n', arr_row)
OutputSuccess
Important Notes

Using np.newaxis does not copy the data, so it is memory efficient.

You can add multiple new axes by using np.newaxis multiple times in indexing.

Remember that np.newaxis is just an alias for None in array slicing.

Summary

np.newaxis adds a new dimension to an array without copying data.

It helps reshape arrays for math operations and machine learning inputs.

You use it by placing np.newaxis inside the array index brackets.