Adding a New Dimension to a NumPy ndarray at First Axis

Answered using GPT-4o by GPT4oMini.app

Question:

add a new dimension at the first axis of an ndarray

Answer:

To add a new dimension at the first axis of a NumPy ndarray, you can use the numpy.expand_dims function or simply use numpy.newaxis. Here are examples of both methods:

Using numpy.expand_dims

import numpy as np

# Create a sample ndarray
arr = np.array([1, 2, 3, 4])

# Add a new dimension at the first axis
new_arr = np.expand_dims(arr, axis=0)

print(new_arr)
print(new_arr.shape)

Using numpy.newaxis

import numpy as np

# Create a sample ndarray
arr = np.array([1, 2, 3, 4])

# Add a new dimension at the first axis
new_arr = arr[np.newaxis, :]

print(new_arr)
print(new_arr.shape)

In both cases, the output will be:

[[1 2 3 4]]
(1, 4)

This shows that a new dimension has been added at the first axis, changing the shape of the array from (4,) to (1, 4).