NumPy 数据类型

在 NumPy 中,“数据类型” 指的是数组中元素的类型。NumPy 提供了丰富的数据类型,用于存储不同类型的数据。

NumPy 常用数据类型

NumPy 支持比 Python 内置类型更多的数据类型。对于 NumPy 来说,它常用的数据类型有以下几种。

  • int32:32 位整数。
  • int64:64 位整数。
  • float32:32 位浮点数。
  • float64:64 位浮点数。
  • complex:128 位复数。
  • bool_:布尔值。
  • string_:字符串。

NumPy ​不需要我们强制指定数据类型,它会根据输入数据自动推断数据类型(dtype)。不过,​手动指定数据类型在某些情况下非常有用,比如可以优化内存使用或确保计算精度。

1. 自动推断数据类型

当创建数组时,NumPy 会根据输入数据自动选择合适的数据类型。其中,NumPy 的默认数据类型取决于输入数据:

  • 整数:int64(64 位整数)。
  • 浮点数:float64(64 位浮点数)。
  • 复数:complex128(128 位复数)。

示例 1:NumPy 自动推断类型

import numpy as np

# 整数数组
arr1 = np.array([1, 2, 3])
print(arr1.dtype)             # 输出: int64

# 浮点数数组
arr2 = np.array([1.0, 2.0, 3.0])
print(arr2.dtype)             # 输出: float64

# 混合类型数组
arr3 = np.array([1, 2.0, 3])
print(arr3.dtype)             # 输出: float64(自动提升为浮点数)

运行结果如下。

int64
float64
float64

2. 手动指定数据类型

我们可以通过 dtype 参数,来显式指定数组的数据类型。这在以下场景中非常有用:

  • 优化内存:使用更小的数据类型(如 int8 或 float32)来减少内存占用。
  • 确保精度:使用更高精度的数据类型(如 float64 或 complex128)来避免计算误差。
  • 兼容性:确保数据与其他系统或库兼容。

示例 2:NumPy 手动指定类型

import numpy as np

# 指定为 32 位整数
arr1 = np.array([1, 2, 3], dtype=np.int32)
print(arr1.dtype)

# 指定为 16 位浮点数
arr2 = np.array([1.0, 2.0, 3.0], dtype=np.float16)
print(arr2.dtype)

运行结果如下。

int32
float16

分析:

如果不使用 dtype 参数显式指定数据类型,那么 NumPy 就会使用默认的数据类型例如,整数默认为 int64,浮点数默认为 float64。

在上面例子中,arr1 被显式指定为 32 位整数 (int32),而 arr2 被显式指定为 16 位浮点数 (float16)。这样做可以更精确地控制数据类型,并可能优化内存使用。

提示: NumPy 会自动推断数据类型,但通过手动指定 dtype 参数却可以优化内存、确保精度或满足特定需求。

NumPy 判断数据类型

在 NumPy 中,我们可以使用 dtype 属性来返回数组的数据类型。这个属性在之前已经接触过很多次了。

示例 3:元素的数据类型一致

import numpy as np

arr1 = np.array([1, 2, 3])
print(arr1.dtype)

arr2 = np.array([1.0, 2.0, 3.0])
print(arr2.dtype)

arr3 = np.array([1+2j, 2+3j, 3+4j])
print(arr3.dtype)

运行结果如下。

int64
float64
complex128

分析:

可能有小伙伴会问:“如果数组元素有一部分是整数,一部分是浮点数,那么此时 dtype 属性返回的是什么呢?” 我们可以来看一下下面例子。

示例 4:元素的数据类型不一致

import numpy as np

arr1 = np.array([1, 2.0, 3])
print(arr1.dtype)

arr2 = np.array([1.0, 2, 3.0])
print(arr2.dtype)

运行结果如下。

float64
float64

分析:

从结果可以看出,当数组元素不一致时,数据类型最终以精度高的为准。实际上,NumPy 会将精度低的元素自动提升为精度高的元素,比如:

import numpy as np
arr = np.array([1, 2.0, 3])
print(arr)         # 输出:[1.0 2.0 3.0]

NumPy 转换数据类型

在 NumPy 中,我们可以使用 ndarray 对象的 astype() 方法来将数组的数据类型从 “一种类型” 转换为 “另一种类型” 。

示例 5:astype() 转换类型

import numpy as np

arr = np.array([1, 2, 3])
print(arr.dtype)

result = arr.astype(np.float64)
print(result.dtype)

运行结果如下。

int64
float64

分析:

在上面例子中,我们使用 astype() 方法将数组从 “int64” 类型转换为 “float64” 类型。

上一篇: NumPy 和 Pandas 的区别

下一篇: NumPy 数组

给站长反馈

绿叶网正在不断完善中,小伙伴们如果发现任何问题,还望多多给站长反馈,谢谢!

邮箱:lvyenet@vip.qq.com

「绿叶网」服务号
绿叶网服务号放大
关注服务号,微信也能看教程。
绿叶网服务号