In Python, 'np.newaxis' is a special constant used to increase the dimension of an array by one. It's often used in array slicing and indexing operations to add a new axis or dimension to an array.

For example, if we have a 1D array of shape (3,), we can use 'np.newaxis' to convert it to a 2D array of shape (3,1) or (1,3) by adding a new axis:

import numpy as np

a = np.array([1, 2, 3])  # shape (3,)
b = a[:, np.newaxis]     # shape (3,1)
c = a[np.newaxis, :]     # shape (1,3)

In the above example, 'a[:, np.newaxis]' creates a new axis along the second dimension (columns) and expands the array to shape (3,1), while 'a[np.newaxis, :]' creates a new axis along the first dimension (rows) and expands the array to shape (1,3).

The 'np.newaxis' constant is equivalent to 'None', and can be used interchangeably in most cases.

NumPy np.newaxis: Increase Array Dimension in Python

原文地址: https://www.cveoy.top/t/topic/nrUL 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录