【问题标题】:How does numpy determine the array data type when it contains multiple dtypes?numpy 包含多个 dtype 时如何确定数组数据类型?
【发布时间】:2018-09-19 22:01:48
【问题描述】:

我正在尝试使用 numpy,当我遇到以下数据类型时 使用内置方法 dtype。按照我得到的几个结果。 你能解释一下u11是什么意思吗

a1 = np.array([3,5,'p'])
print(a1.dtype)

o/p = >U11

【问题讨论】:

标签: python numpy numpy-dtype


【解决方案1】:

Numpy 的 PyArrayObject 类型的数组对象有一个 NPY_PRIORITY 属性,该属性表示在数组包含具有异构数据类型的项目的情况下项目类型的优先级。您可以使用 PyArray_GetPriority API 访问此优先级,该 API 返回 __array_priority__ 属性,根据文档:

class.__array_priority__ : 该属性的值用于 确定在存在的情况下返回什么类型的对象 返回对象的 Python 类型的可能性不止一种。 子类继承此属性的默认值 0.0。

现在,在这种情况下,Unicode 的优先级高于整数类型,这就是a1.dtype 返回U11 的原因。

关于U11或者一般的U#,需要注意的是它由两部分组成; U 表示 Unicode dtype# 表示它可以容纳的元素数量——但在不同的平台上可能会有所不同。

In [45]: a1.dtype
Out[45]: dtype('<U21')  # 64bit Linux

In [46]: a1.dtype.type  # The type object used to instantiate a scalar of this data-type. 
Out[46]: numpy.str_

In [49]: a1.dtype.itemsize
Out[49]: 84 # 21 * 4

在文档https://docs.scipy.org/doc/numpy-1.14.0/reference/arrays.dtypes.html#data-type-objects-dtype 中阅读有关字符串类型和其他数据类型对象的更多详细信息。

【讨论】:

  • 感谢您的解释
猜你喜欢
  • 1970-01-01
  • 2021-05-02
  • 2020-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-20
相关资源
最近更新 更多