ITPub博客

首页 > 人工智能 > 人工智能 > 人工智能之数据分析 numpy:第四章 数组属性和数据类型

人工智能之数据分析 numpy:第四章 数组属性和数据类型

原创 人工智能 作者:咚咚王者 时间:2025-11-23 17:20:01 0 删除 编辑

人工智能之数据分析 numpy

第四章 数组属性和数据类型



前言

NumPy 的 ndarray(N 维数组) 不仅是一个高效的多维容器,还具有丰富的 属性和灵活的 数据类型(dtype)系统。理解这些内容对于高效使用 NumPy 至关重要。


一、NumPy 数组的核心属性

创建一个示例数组:

import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float32)

1. ndim:数组的维度数(轴的数量)

print(arr.ndim)  # 输出:2

2. shape:数组在每个维度上的大小(元组)

print(arr.shape)  # 输出:(2, 3) → 2行3列

3. size:数组中元素的总个数

print(arr.size)  # 输出:6(= 2 × 3)

4. dtype:数组元素的数据类型

print(arr.dtype)  # 输出:float32

5. itemsize:每个元素占用的字节数

print(arr.itemsize)  # 输出:4(因为 float32 占 4 字节)

6. nbytes:整个数组占用的总字节数(= size × itemsize)

print(arr.nbytes)  # 输出:24(6 × 4)

7. data:底层数据的内存地址(一般不直接使用)

print(arr.data)  # <memory at 0x...>

⚠️ 注意: data 属性返回的是缓冲区对象,不是实际数据内容。要访问数据,请直接使用数组本身。


二、NumPy 数据类型(dtype)

NumPy 支持比 Python 原生更丰富、更精确的数值类型,尤其适合科学计算。

1. 常见 dtype 类型

| 类型名                                             | 描述                 | 对应 C 类型                        | 示例                     |

| ---------------------------------------------------- | ---------------------- | ------------------------------------ | -------------------------- |

| bool_                                        | 布尔值(True/False) | bool                               | np.bool_           |

| int8, int16, int32, int64     | 有符号整数           | char, short, int, long long        | np.int32           |

| uint8, uint16, uint32, uint64 | 无符号整数           | unsigned char 等                   | np.uint8           |

| float16, float32, float64          | 浮点数               | half, float, double                | np.float64(默认) |

| complex64, complex128                   | 复数                 | float + float i, double + double i | np.complex128      |

💡 在大多数系统上:

  • np.int_ ≡ np.int64(64 位系统)
  • np.float_ ≡ np.float64

2. 指定 dtype 创建数组

a = np.array([1, 2, 3], dtype='int32')
b = np.zeros(5, dtype=np.float64)
c = np.array([1.5, 2.7], dtype=np.float32)

3. 查看和修改 dtype

  • 查看:

`` python   print(a.dtype)  # int32   ``

  • 转换(返回新数组):

`` python   d = a.astype(np.float64)   print(d.dtype)  # float64   ``

⚠️ astype() 会创建副本,除非 dtype 相同。

4. 自定义结构化 dtype(用于记录型数据)

适用于类似表格或结构体的数据:

dt = np.dtype([('name', 'U10'), ('age', 'i4'), ('weight', 'f4')])
people = np.array([('Alice', 25, 55.5), ('Bob', 30, 70.0)], dtype=dt)
print(people['name'])    # ['Alice' 'Bob']
print(people[0]['age'])  # 25
  • 'U10' 表示 Unicode 字符串,最多 10 个字符
  • 'i4' 表示 4 字节整数(即 int32)
  • 'f4' 表示 4 字节浮点数(float32)

三、数据类型字符串表示(简写)

NumPy 允许使用字符串简写指定 dtype:

字符串 含义
'i4' 32 位整数
'f8' 64 位浮点数
'U10' 最大长度为 10 的 Unicode 字符串
'bool' 布尔值
'c8' 64 位复数(两个 32 位浮点)

示例:

x = np.array([1, 2], dtype='f4')  # 等价于 np.float32

四、dtype 的属性(了解即可)

t = np.dtype('float64')
print(t.name)      # 'float64'
print(t.itemsize)  # 8
print(t.kind)      # 'f'(f=float, i=int, U=unicode string, b=bool 等)

常见 kind 值:

  • 'b': boolean
  • 'i': signed integer
  • 'u': unsigned integer
  • 'f': floating-point
  • 'c': complex floating-point
  • 'U': Unicode string
  • 'O': Python object

五、注意事项与最佳实践

  1. 避免不必要的 dtype 转换:频繁 astype() 会降低性能。
  2. 内存效率:使用合适精度的类型(如用 float32 代替 float64 可节省 50% 内存)。
  3. 整数溢出:注意 int8 范围是 -128\~127,超出会回绕(不报错!)。

`` python    x = np.array([127], dtype='int8')    print(x + 1)  # [-128] ← 溢出!    ``

  1. 默认 dtype:
  • 整数列表 → int64(64 位系统)
  • 浮点列表 → float64
  • 混合(如 [1, 2.0])→ float64

六、小结表:常用属性与 dtype 对照

属性/操作 说明
arr.ndim 维度数量
arr.shape 各维度大小
arr.size 元素总数
arr.dtype 数据类型
arr.itemsize 单个元素字节数
arr.astype(new_dtype) 类型转换
np.dtype([...]) 自定义结构化类型

在处理图像(常用 uint8)、深度学习(常用 float32)或金融数据(需高精度 float64),选择合适的 dtype 能显著提升性能和内存效率。

后续

部分代码已经上传至gitee,后续会逐步更新,主要受时间原因限制,当然自己也可以克隆到本地学习拓展。

资料关注

公众号:咚咚王 gitee: https://gitee.com/wy18585051844/ai_learning

《Python编程:从入门到实践》 《利用Python进行数据分析》 《算法导论中文第三版》 《概率论与数理统计(第四版) (盛骤) 》 《程序员的数学》 《线性代数应该这样学第3版》 《微积分和数学分析引论》 《(西瓜书)周志华-机器学习》 《TensorFlow机器学习实战指南》 《Sklearn与TensorFlow机器学习实用指南》 《模式识别(第四版)》 《深度学习 deep learning》伊恩·古德费洛著 花书 《Python深度学习第二版(中文版)【纯文本】 (登封大数据 (Francois Choliet)) (Z-Library)》 《深入浅出神经网络与深度学习+(迈克尔·尼尔森(Michael+Nielsen)》 《自然语言处理综论  第2版》 《Natural-Language-Processing-with-PyTorch》 《计算机视觉-算法与应用(中文版)》 《Learning OpenCV 4》 《AIGC:智能创作时代》杜雨+&+张孜铭 《AIGC原理与实践:零基础学大语言模型、扩散模型和多模态模型》 《从零构建大语言模型(中文版)》 《实战AI大模型》 《AI 3.0》

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70048224/viewspace-3103053/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论
深耕人工智能领域,做你的随身笔记。

注册时间:2025-10-26

  • 博文量
    47
  • 访问量
    46037