Python中如何将列表内的numpy数组从(1,n,n)缩减至(n,n)
通用NumPy数组重塑方案
针对将形状为(1, n, n)的NumPy数组转换为(n, n)的需求,以下是几种通用实现方式:
1. 基于数组形状属性的reshape
直接利用数组的shape属性动态获取维度大小,无需硬编码数值:
import numpy as np # 示例输入数组 arr = np.array([[[1, 2, 3], [4, 5, 6], [7, 8, 9]]]) # 通用重塑操作 arr_reshaped = arr.reshape(arr.shape[1], arr.shape[2]) print(arr_reshaped.shape) # 输出: (3, 3)
2. 使用squeeze移除单维度
如果数组仅存在长度为1的维度,squeeze()可直接移除所有这类维度,适配性更强(比如也能处理(n, 1, n)这类形状):
import numpy as np arr = np.array([[[1, 2, 3], [4, 5, 6], [7, 8, 9]]]) arr_reshaped = arr.squeeze() print(arr_reshaped.shape) # 输出: (3, 3)
3. 切片跳过单维度
针对第一个维度固定为1的场景,直接通过切片跳过该维度,获取目标二维数组:
import numpy as np arr = np.array([[[1, 2, 3], [4, 5, 6], [7, 8, 9]]]) arr_reshaped = arr[0] print(arr_reshaped.shape) # 输出: (3, 3)
内容的提问来源于stack exchange,提问作者user19862793
相关产品推荐
相关产品推荐

