简体   繁体   English

np.ndarray 可以用自定义 dtype 注释吗?

[英]Can np.ndarray be annotated with a custom dtype?

We can create custom dtypes with record-like properties:我们可以创建具有类似记录属性的自定义数据类型

dt = np.dtype([('R','u1'), ('G','u1'), ('B','u1'), ('A','u1')])

We can annotate the data type of an ndarray for type hinting:我们可以为类型提示注释 ndarray 的数据类型

numpy.typing.NDArray = numpy.ndarray[typing.Any, numpy.dtype[+ScalarType]]

However, I can't work out how to hint that an array is supposed to have a custom dtype, for instance a: NDArray[dt] results in Pylance complaining:但是,我无法弄清楚如何暗示数组应该具有自定义 dtype,例如a: NDArray[dt]导致 Pylance 抱怨:

Declared return type, "ndarray[Any, dtype[Unknown]]", is partially unknown Pylance(reportUnknownVariableType)
Illegal type annotation: variable not allowed unless it is a type alias Pylance(reportGeneralTypeIssues)

I guess what I'm asking is if is possible to create a type from a dtype object, or what the +ScalarType means in numpy.ndarray[typing.Any, numpy.dtype[+ScalarType]] .我想我要问的是是否可以从 dtype object 创建类型,或者 +ScalarType 在numpy.ndarray[typing.Any, numpy.dtype[+ScalarType]]中的含义。

An array with a compound dtype like this:具有复合 dtype 的数组,如下所示:

In [98]: dt = np.dtype([('R','u1'), ('G','u1'), ('B','u1'), ('A','u1')])
In [99]: arr = np.ones(3, dt)
In [100]: arr
Out[100]: 
array([(1, 1, 1, 1), (1, 1, 1, 1), (1, 1, 1, 1)],
      dtype=[('R', 'u1'), ('G', 'u1'), ('B', 'u1'), ('A', 'u1')])

The elements of this array of type, np.void这个类型数组的元素, np.void

In [101]: type(arr[0])
Out[101]: numpy.void
In [102]: arr.dtype
Out[102]: dtype([('R', 'u1'), ('G', 'u1'), ('B', 'u1'), ('A', 'u1')])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM