0
0
NumpyHow-ToBeginner ยท 3 min read

How to Use np.newaxis in NumPy for Array Reshaping

Use np.newaxis in NumPy to add a new dimension to an existing array, which helps reshape it for operations like broadcasting. It is used by placing np.newaxis inside the array indexing brackets to increase the array's dimensionality by one.
๐Ÿ“

Syntax

The syntax to use np.newaxis is by inserting it inside the square brackets when indexing an array. For example, array[:, np.newaxis] adds a new axis as a column.

  • array: Your original NumPy array.
  • np.newaxis: A special object that adds a new dimension.
  • Placing np.newaxis in the index increases the array's dimensions by one at that position.
python
import numpy as np

arr = np.array([1, 2, 3])
print(arr.shape)  # Original shape

arr_new = arr[:, np.newaxis]
print(arr_new.shape)  # Shape after adding newaxis
Output
(3,) (3, 1)
๐Ÿ’ป

Example

This example shows how np.newaxis changes a 1D array into a 2D column vector, which is useful for broadcasting in operations like addition or multiplication.

python
import numpy as np

arr = np.array([10, 20, 30])
print("Original array shape:", arr.shape)

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

# Create a row vector
arr_row = arr[np.newaxis, :]
print("Row vector shape:", arr_row.shape)

# Broadcasting example: add column vector to row vector
result = arr_col + arr_row
print("Result of broadcasting addition:\n", result)
Output
Original array shape: (3,) New array shape: (3, 1) Row vector shape: (1, 3) Result of broadcasting addition: [[20 30 40] [30 40 50] [40 50 60]]
โš ๏ธ

Common Pitfalls

Common mistakes include:

  • Using np.newaxis outside of indexing brackets, which causes errors.
  • Confusing np.newaxis with reshape() or expand_dims() methods.
  • Adding new axes in the wrong position, leading to unexpected shapes.

Always check the shape after adding np.newaxis to ensure it matches your intended array structure.

python
import numpy as np

arr = np.array([1, 2, 3])

# Wrong usage: np.newaxis outside indexing
try:
    arr_wrong = np.newaxis(arr)
except TypeError as e:
    print("Error:", e)

# Correct usage
arr_correct = arr[:, np.newaxis]
print("Correct shape:", arr_correct.shape)
Output
Error: 'numpy.newaxis' object is not callable Correct shape: (3, 1)
๐Ÿ“Š

Quick Reference

UsageEffectExample
Add new axis as columnTurns (N,) into (N,1)arr[:, np.newaxis]
Add new axis as rowTurns (N,) into (1,N)arr[np.newaxis, :]
Add axis in middleIncreases dimension at positionarr[:, np.newaxis, :]
Use for broadcastingAlign shapes for operationsarr1[:, np.newaxis] + arr2[np.newaxis, :]
โœ…

Key Takeaways

Use np.newaxis inside array indexing to add a new dimension to an array.
Adding a new axis changes the shape, enabling broadcasting and reshaping without copying data.
Place np.newaxis carefully to get the desired dimension position.
Do not call np.newaxis like a function; it must be used inside brackets.
Check array shapes after adding new axes to avoid shape mismatches.