智算多多联系我们


关注我们

公众号

视频号
隐私协议用户协议
◎ 2025 北京智算多多科技有限公司版权所有京ICP备 2025150592号-1
reshape() 是 NumPy 中最常用的数组重塑函数,它允许我们在不改变数组数据的情况下,重新组织数组的维度结构。
import numpy as np
# 创建一维数组
arr_1d = np.arange(12)
print(f"原始数组: {arr_1d}")
print(f"原始形状: {arr_1d.shape}")
# 重塑为 3x4 矩阵
arr_2d = arr_1d.reshape(3, 4)
print(f"\n重塑为 3x4:\n{arr_2d}")
print(f"新形状: {arr_2d.shape}")
# 重塑为 2x2x3 三维数组
arr_3d = arr_1d.reshape(2, 2, 3)
print(f"\n重塑为 2x2x3:\n{arr_3d}")
print(f"新形状: {arr_3d.shape}")
一键获取完整项目代码
重塑规则:
- 元素总数不变:重塑前后数组的元素总数必须相等
- 内存连续性:
reshape()返回的是原数组的视图(view),不会复制数据- 自动推断:可以使用
-1让 NumPy 自动计算某个维度的大小