numpy np.newaxis介绍
np.newaxis
是 NumPy 中用于增加数组维度的关键字。它的作用是为数组插入一个新的维度,从而改变数组的形状(shape)。
基本用法
np.newaxis
等价于None
,可以作为索引使用,用于在指定位置增加一个维度。- 增加的维度的大小为
1
。
语法
array[newaxis, ...] # 在第 0 维增加一个维度
array[..., newaxis] # 在最后一维增加一个维度
array[:, newaxis, :] # 在指定位置增加一个维度
例子与解释
1. 在第 0 维增加一个维度
import numpy as nparr = np.array([1, 2, 3]) # 原始数组 shape: (3,)
new_arr = arr[np.newaxis, :] # shape: (1, 3)print(new_arr)
# Output:
# [[1 2 3]]
解释:
- 原始数组
arr
是一维的,形状为(3,)
。 - 使用
np.newaxis
后,在第 0 维增加一个新维度,形状变为(1, 3)
。
2. 在最后一维增加一个维度
arr = np.array([1, 2, 3]) # shape: (3,)
new_arr = arr[:, np.newaxis] # shape: (3, 1)print(new_arr)
# Output:
# [[1]
# [2]
# [3]]
解释:
- 原始数组
arr
是一维的,形状为(3,)
。 - 使用
np.newaxis
后,在最后一维增加一个新维度,形状变为(3, 1)
。
3. 用于多维数组
arr = np.array([[1, 2, 3], [4, 5, 6]]) # shape: (2, 3)# 在第 0 维增加
new_arr_1 = arr[np.newaxis, :, :] # shape: (1, 2, 3)# 在第 1 维增加
new_arr_2 = arr[:, np.newaxis, :] # shape: (2, 1, 3)# 在最后一维增加
new_arr_3 = arr[:, :, np.newaxis] # shape: (2, 3, 1)print("Original Shape:", arr.shape)
print("Shape after newaxis at dim 0:", new_arr_1.shape)
print("Shape after newaxis at dim 1:", new_arr_2.shape)
print("Shape after newaxis at dim 2:", new_arr_3.shape)
实际应用
1. 转换向量为列向量或行向量
在机器学习或矩阵运算中,常需要将向量变为列向量或行向量。
arr = np.array([1, 2, 3]) # shape: (3,)# 转为列向量
col_vector = arr[:, np.newaxis] # shape: (3, 1)# 转为行向量
row_vector = arr[np.newaxis, :] # shape: (1, 3)print("Column Vector:\n", col_vector)
print("Row Vector:\n", row_vector)
2. 扩展广播机制
使用 np.newaxis
可以调整数组形状以实现广播操作。
arr1 = np.array([1, 2, 3]) # shape: (3,)
arr2 = np.array([4, 5]) # shape: (2,)# 调整维度
arr1_expanded = arr1[np.newaxis, :] # shape: (1, 3)
arr2_expanded = arr2[:, np.newaxis] # shape: (2, 1)result = arr1_expanded + arr2_expanded # shape: (2, 3)print(result)
# Output:
# [[5 6 7]
# [6 7 8]]
等价性
np.newaxis
等价于 None
,下面两种写法是相同的:
arr = np.array([1, 2, 3])# 使用 np.newaxis
new_arr_1 = arr[np.newaxis, :]# 使用 None
new_arr_2 = arr[None, :]print(np.array_equal(new_arr_1, new_arr_2)) # Output: True
总结
np.newaxis
是一种增加数组维度的简单方法,实质是为数组插入大小为1
的新维度。- 常用于:
- 调整数组形状(如向量转列/行向量)。
- 配合广播机制使用。
- 为高维数据的操作做准备。
- 使用方式简单直观,可以通过指定插入位置灵活控制新维度的位置。