Numpy 如何推断数组的 dtype

How does Numpy infers dtype for array

任何人都可以帮助我理解 Numpy 的数组函数从哪里推断数据类型。

我理解它基本上是从分配给数组的值的种类推断出来的。

例如:

> data = [1,2,3,4]
> arr = np.array(data)

所以在上面的行中,"arr" 将有 dtype('int64')dtype('int32')

我想了解的是它如何决定是给它 int64 还是 int32

我知道这可能是一个微不足道的问题,但我只是想了解它是如何工作的,因为我最近在一次采访中被问到这个问题。

数值数据类型包括整数和浮点数。

如果我们有一个包含integersfloating point numbers的数组,numpy会将整个数组分配给float数据类型,所以小数点不是迷路了。

整数永远不会有小数点。因此,例如,2.55 将存储为 2

如@unutbu所述 int32int64 取决于您拥有的位机类型,是 32 位机还是 64 位机

Strings,是包含numbersand/orcharacters的值。例如,一个字符串可能是一个词、一个句子或几个句子。如果您的数组具有混合类型(数字和字符串),则最通用的 dtype=string 将分配给您的数组。

要完整详细的看一下,可以看看this website of scipy docs

the docs,

Some types, such as int and intp, have differing bitsizes, dependent on the platforms (e.g. 32-bit vs. 64-bit machines).

因此,在 32 位机器上,np.array([1,2,3,4]) returns dtype int32 数组,但在 64 位机器上 returns dtype int64.

我认为存在某种分级处理方式,它使用可以 "legally" 表示输入的最保守但又包罗万象的类型。如果您只有整数,您将使用 int32/64 保留所有元素。一旦引入浮点数,就需要使用 float32/64 来保留数组的所有元素,并且始终可以将 float 反向转换为 int。一旦引入字符串,就需要使用字符串合法地表示数组中的所有内容,同样,如果需要 [=15=,则始终可以反向转换为 floatint ]

例如:

>>> array([1]).dtype
dtype('int64')
>>> array([1, 2.0]).dtype
dtype('float64')
>>> array([1, 2.0, 'a']).dtype
dtype('S3')

简而言之,它非常聪明;)

在Python3(和基本的 32 位机器)中,int32 v int64 取决于输入的大小

In [447]: np.array(123456789)
Out[447]: array(123456789)

In [448]: _.dtype
Out[448]: dtype('int32')

In [449]: np.array(12345678901234)
Out[449]: array(12345678901234, dtype=int64)

来自 np.array 文档:

dtype: The desired data-type for the array. If not given, then the type will be determined as the minimum type required to hold the objects in the sequence. This argument can only be used to 'upcast' the array.

看起来 int32 是最小的默认 int 大小(至少对于我的配置)。也是 np.int_.

的值

作为不允许的向下转换的示例:

In [456]: np.array(12345678901234, dtype=np.int32)
---------------------------------------------------------------------------
OverflowError                             Traceback (most recent call last)
<ipython-input-456-da7c96e4b0b3> in <module>()
----> 1 np.array(12345678901234, dtype=np.int32)

OverflowError: Python int too large to convert to C long