我试图理解Numpy中dtypes的逻辑.
numpy.min_scalar_type(10)
-> uint8
和:
a = numpy.array([10])
print(a.dtype)
-> int32 (on my machine)
我期待uint8而不是int32,因为(1.9)doc说:
numpy.array(object, dtype=None, …)
dtype : data-type, optional. 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
和:
numpy.min_scalar_type(a)
For scalar a, returns the data type with the smallest size and
smallest scalar kind which can hold its value.
…
Returns: out : dtype. The minimal data type.
我误解了什么吗?
解决方法:
python列表可以包含不同类型的对象,例如X = [‘apples’,’oranges’,10].如果你输入([10]),你会发现容器的Python类型在技术上被称为列表,而不是数组.
相反,在numpy数组中,所有对象都是相同类型的dtype.
文档告诉您,在创建numpy数组时,dtype设置为将包含所有现有对象的类型.
看,看:
the type will be determined as the minimum type required to hold the objects in the sequence
作家或许应该加上“而不是他们的价值观”
我们可以轻松地制作一个uint8:
ten = np.uint8(10)
如果将它放入Python列表中,它会保留其类型,因为Python列表会保留类型.如果将该列表发送到numpy.array()以生成numpy数组,则numpy数组将使用dtype np.uint8,因为它足以容纳所有(1)预先存在的Python列表对象.
In [49]: np.array([ten]).dtype
Out[49]: dtype('uint8')
但是如果我们使用文字10,python将为它而不是np.uint8创建一个int对象,因为np.uint8是numpy特有的,而且所有10都调用python来创建该数字.
如果我们创建一个包含文字10的Python列表,我们会复制您的结果(使用机器架构整数):
In [50]: np.array([10]).dtype
Out[50]: dtype('int64')
如果我们将这两种类型放在一个python列表中,并将该列表发送到np.array以创建一个numpy数组,那么dtype必须足够大以容纳两个对象,在本例中为int64.
In [51]: np.array([ten, 10]).dtype
Out[51]: dtype('int64')
标签:python,numpy