python numpy dtype object_python – numpy.array()中的dtype参数

我试图理解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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值