创建数组时 dtype = np.int 和 int 的区别

Difference between dtype = np.int and int when creating array

我对整数类型之间的区别感到困惑。

例如,这里有一个 numpy.array,dtype 为 np.int

>>> arr_ = np.array([1,2], dtype = np.int)

通过下面的代码,表示trueintnp.int相同:

>>> int is np.int
Out[1]: True

但是,当我 select 使用 np.int 的 dtype 创建的数组的第一个值时,下面的代码输出 false.

>>> type(arr_[0]) is int
Out[2]: False

为什么代码输出的是false,而不是true

dtype = np.int 似乎没有应用于 arr_

为什么 np.int 没有作为数据类型应用于数组?

我调查了 this,但找不到我需要的东西。

在 Python 中,类型 intnp.int32np.int64 是 3 种不同的类型:

  • int 是原生的 Python 多精度整数类型,能够表示任何整数值(唯一的限制是可用内存)。例如 2**128 是一个有效的 int
  • np.int32int32_t C 整数类型中,最多可以使用 32 位来表示值,即介于 -2147483648 和 2147483647 之间的值
  • np.int64int64_t C 整数类型,最多可以使用 64 位来表示值,即介于 -9223372036854775808 和 9223372036854775807
  • 之间的值

np.int 是本机 Python int 类型的(已弃用的别名),int is np.int 的原因是正确的。但是即使 dtype=int 的 numpy 整数数组也会收到 np.int32np.int64 的实际类型,因为它们必须由 C 代码处理,因此它们必须被强制转换为固定大小的整数类型。如果你真的需要存储真实的 int 值,你将不得不使用 dtype=object 但操作将不再是向量化的。