📌 写在前面
大家好!👋
欢迎来到**【一起学Python】**的第77天!
前两天我们学习了ndarray对象和数据类型,今天我们来解锁NumPy的核心属性!
🤔 为什么要学数组属性?
- ✅ 快速了解数组的结构和规模
- ✅ 调试代码时的必备技能
- ✅ 数据预处理、模型输入的关键步骤
- ✅ 避免"维度不匹配"报错的救命稻草
今天你将学到:
- 🔸 shape、ndim、size 三大核心属性
- 🔸 dtype、itemsize、nbytes 内存相关属性
- 🔸 reshape() 重塑数组的实用技巧
- 🔸 实际案例:图像数据的维度变换
准备好了吗?让我们开始吧!🚀
一、数组属性速览 📊
1.1 6大核心属性一图看懂
📦 NumPy数组属性├── 🔷 结构属性│ ├── shape : 数组形状(元组)✅ 最常用│ ├── ndim : 维度数量(整数)│ └── size : 元素总数(整数)│├── 🔷 内存属性│ ├── dtype : 元素数据类型│ ├── itemsize: 单个元素字节数│ └── nbytes : 数组总字节数│└── 💡 记忆口诀:形状维度看size,内存占用看nbytes
1.2 实战演示:一键查看所有属性
import numpy as np# 创建一个3×4的二维数组arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])print("📊 数组属性速查")print(f"数组内容:\n{arr}\n")print(f"shape : {arr.shape}") # (3, 4)print(f"ndim : {arr.ndim}") # 2print(f"size : {arr.size}") # 12print(f"dtype : {arr.dtype}") # int64print(f"itemsize: {arr.itemsize}") # 8print(f"nbytes : {arr.nbytes}") # 96
✅ shape=(3,4) → 3行4列✅ ndim=2 → 二维数组✅ size=12 → 总共12个元素✅ dtype=int64 → 每个元素是64位整数✅ itemsize=8 → 每个元素占8字节✅ nbytes=96 → 12×8=96字节总内存
二、核心属性详解 🔍
2.1 shape:数组的"身材"
# 一维数组arr1 = np.array([1, 2, 3, 4, 5])print("一维:", arr1.shape) # (5,)# 二维数组arr2 = np.array([[1, 2, 3], [4, 5, 6]])print("二维:", arr2.shape) # (2, 3)# 三维数组(比如RGB图像)arr3 = np.zeros((28, 28, 3))print("三维:", arr3.shape) # (28, 28, 3)# 解读:28×28像素,3个颜色通道
# 获取行数/列数rows, cols = arr2.shapeprint(f"{rows}行{cols}列") # 2行3列# 动态适配任意维度print("最后一个维度:", arr2.shape[-1]) # 3
2.2 ndim & size:维度和总量
# 不同维度的ndim对比arr_1d = np.array([1, 2, 3])arr_2d = np.array([[1, 2], [3, 4]])arr_3d = np.array([[[1]], [[2]]])print(f"1D数组: ndim={arr_1d.ndim}, size={arr_1d.size}")print(f"2D数组: ndim={arr_2d.ndim}, size={arr_2d.size}")print(f"3D数组: ndim={arr_3d.ndim}, size={arr_3d.size}")
1D数组: ndim=1, size=32D数组: ndim=2, size=43D数组: ndim=3, size=2
2.3 内存属性:精准控制资源
# 对比不同数据类型的内存占用arr_int8 = np.zeros(1000, dtype=np.int8)arr_int64 = np.zeros(1000, dtype=np.int64)print(f"int8 : {arr_int8.nbytes} 字节") # 1000字节print(f"int64 : {arr_int64.nbytes} 字节") # 8000字节# 💡 结论:选对类型,内存节省8倍!
三、属性修改实战:reshape() ✨
3.1 reshape():重塑数组形状
# 创建12个元素的一维数组arr = np.arange(12)print("原数组:", arr)print("原shape:", arr.shape) # (12,)# 重塑为3×4的二维数组arr_2d = arr.reshape(3, 4)print("\n重塑后:\n", arr_2d)print("新shape:", arr_2d.shape) # (3, 4)# 重塑为2×3×2的三维数组arr_3d = arr.reshape(2, 3, 2)print("\n三维数组:\n", arr_3d)print("新shape:", arr_3d.shape) # (2, 3, 2)
✅ 重塑前后元素总数必须相同✅ 可以使用 -1 让NumPy自动计算维度# 示例:自动计算列数arr = np.arange(12)result = arr.reshape(3, -1) # 3行,列数自动计算print(result.shape) # (3, 4)
3.2 其他形状操作技巧
# 转置:行列互换arr2d = np.array([[1, 2, 3], [4, 5, 6]])print("原数组:\n", arr2d)print("转置后:\n", arr2d.T) # 或 arr2d.transpose()# 展平:多维变一维flat = arr2d.flatten()print("展平后:", flat) # [1 2 3 4 5 6]# 添加/删除维度arr1d = np.array([1, 2, 3])col_vec = arr1d[:, np.newaxis] # 添加新维度print("列向量shape:", col_vec.shape) # (3, 1)
四、实际应用场景 🎨
场景1:图像处理(最经典!)
# 模拟一张28×28的灰度图像gray_img = np.random.randint(0, 256, (28, 28), dtype=np.uint8)print(f"图像尺寸: {gray_img.shape}") # (28, 28)print(f"像素总数: {gray_img.size}") # 784print(f"内存占用: {gray_img.nbytes} 字节") # 784字节# 转换为深度学习需要的格式:(1, 28, 28, 1)# 批次大小=1,高=28,宽=28,通道=1input_tensor = gray_img.reshape(1, 28, 28, 1)print(f"模型输入形状: {input_tensor.shape}")
场景2:表格数据处理
# 模拟100行×5列的数据表data = np.random.randn(100, 5)print(f"数据规模: {data.shape[0]}行 × {data.shape[1]}列")print(f"特征数量: {data.shape[1]}")# 提取某一列(比如第3列)feature_3 = data[:, 2]print(f"单列数据形状: {feature_3.shape}") # (100,)
场景3:批量数据预处理
# 模拟1000个样本,每个样本10个特征X = np.random.randn(1000, 10)# 检查数据形状assert X.ndim == 2, "数据必须是二维!"assert X.shape[0] == 1000, "样本数不匹配!"# 标准化前查看统计信息print(f"均值: {X.mean():.4f}")print(f"标准差: {X.std():.4f}")
📝 今日作业
基础题 ⭐
- 创建一个3×5的数组,打印它的shape、ndim、size
- 使用reshape()将12个元素的一维数组变成4×3的二维数组
- 查看数组的dtype和nbytes,计算理论内存占用
进阶题 ⭐⭐
- 创建一个(2, 3, 4)的三维数组,分别获取每个维度的大小
- 使用-1参数,将24个元素的数组重塑为(3, -1)和(-1, 6)
- 对比int32和float64类型数组的内存占用差异
挑战题 ⭐⭐⭐
- 编写函数:输入任意数组,返回格式化的属性报告
- 模拟图像数据:创建(32, 32, 3)的RGB数组,计算总像素和内存
- 实现数据"展平→重塑"的完整流程,验证数据一致性
import numpy as np# 基础题arr = np.zeros((3, 5))print(f"shape:{arr.shape}, ndim:{arr.ndim}, size:{arr.size}")arr1d = np.arange(12)arr2d = arr1d.reshape(4, 3)print("重塑成功:", arr2d.shape)# 进阶题arr3d = np.random.randn(2, 3, 4)print(f"三维: {arr3d.shape[0]}×{arr3d.shape[1]}×{arr3d.shape[2]}")# 挑战题:属性报告函数def array_report(arr, name="数组"): print(f"\n📊 {name}属性报告") print(f"形状: {arr.shape}") print(f"维度: {arr.ndim}D") print(f"元素数: {arr.size}") print(f"类型: {arr.dtype}") print(f"内存: {arr.nbytes}字节 ({arr.nbytes/1024:.2f}KB)")arr = np.random.randn(100, 50)array_report(arr, "测试数据")
🎓 明日预告
第78天:NumPy创建数组进阶技巧
你将学到:
- 🔸 np.zeros/ones/empty 的进阶用法
- 🔸 np.eye 创建单位矩阵
- 🔸 np.full 填充指定值
- 🔸 从文件加载数组的实用方法
敬请期待!
💡 学习小贴士
- 调试技巧:
- 遇到维度错误?先print(arr.shape)!
- 内存不够?检查dtype和nbytes
- 重塑失败?确认size是否匹配
# 快速创建指定形状的数组arr = np.zeros((100, 50), dtype=np.float32)# 一键查看关键信息print(f"{arr.shape} | {arr.dtype} | {arr.nbytes/1024:.1f}KB")
- reshape()不改变数据,只改变"视图"
- shape返回的是元组,注意索引方式
- 大数组优先用float32节省内存
📚 学习路线图
第74天:NumPy安装 ✓第75天:ndarray对象 ✓第76天:数据类型 ✓第77天:数组属性 ✓ ← 你今天在这里第78天:创建数组进阶第79天:切片和索引第80天:数组运算...
💬 写在最后
数组属性是理解NumPy的钥匙,掌握它们,你就能:
✅ 快速诊断数据问题✅ 精准控制内存使用✅ 轻松对接机器学习框架
今天重点掌握:
- ✅ shape、ndim、size 的含义和使用
- ✅ reshape() 的正确用法
- ✅ 内存属性的实际意义
如果觉得有用,记得:
- 👍 点赞支持一下
- ⭐ 收藏方便复习
- 📤 分享给更多小伙伴
完成作业的同学,欢迎在评论区打卡! 💪
【一起学Python】每天进步一点点,365天后遇见更优秀的自己!
👉 关注公众号,不错过每天的学习内容!
🎯 今日金句:
"shape是数组的身份证,ndim是它的维度护照,掌握它们,数据世界任你穿梭!" 🌍
明天见! 🌟