如何识别python中的numpy类型?

Dou*_*ple 80 python duck-typing numpy dynamic-typing

如何可靠地确定对象是否具有numpy类型?

我意识到这个问题违背了鸭子打字的哲学,但是想法是确保一个函数(使用scipy和numpy)永远不会返回一个numpy类型,除非它被调用numpy类型. 这出现在另一个问题的解决方案中,但我认为确定一个对象是否具有numpy类型的一般问题远远远离它们应该分开的原始问题.

aba*_*ert 92

使用内置type函数获取类型,然后您可以使用该__module__属性找出它的定义位置:

>>> import numpy as np
a = np.array([1, 2, 3])
>>> type(a)
<type 'numpy.ndarray'>
>>> type(a).__module__
'numpy'
>>> type(a).__module__ == np.__name__
True
Run Code Online (Sandbox Code Playgroud)

  • @ j08lue它们不是隐藏的属性,而是有文献记载的特殊属性。尽管如此,它是不可思议的,但是我认为这是问题的固有原因。(而且我认为,Python的优势在于,当您想做某种语言不鼓励的事情时,最好的解决方案通常看上去很丑陋,足以表明您正在做的事情通常是个坏主意。) (2认同)

Dou*_*ple 60

我提出的解决方案是:

isinstance(y, (np.ndarray, np.generic) )
Run Code Online (Sandbox Code Playgroud)

然而,并非100%清楚所有numpy类型都保证是np.ndarray或者np.generic,这可能不是版本强大.


Lin*_*dc3 18

老问题,但我想出了一个明确的答案与一个例子.因为我遇到同样的问题而没有找到明确的答案,所以不能让问题保持新鲜.关键是要确保已numpy导入,然后运行isinstancebool.虽然这看起来很简单,但如果您在不同的数据类型中进行一些计算,这个小的检查可以在您开始一些numpy矢量化操作之前作为快速测试.

##################
# important part!
##################

import numpy as np

####################
# toy array for demo
####################

arr = np.asarray(range(1,100,2))

########################
# The instance check
######################## 

isinstance(arr,np.ndarray)
Run Code Online (Sandbox Code Playgroud)


Rol*_*ith 8

要获取类型,请使用内置type函数.使用in运算符,您可以通过检查类型是否包含字符串来测试类型是否为numpy类型numpy;

In [1]: import numpy as np

In [2]: a = np.array([1, 2, 3])

In [3]: type(a)
Out[3]: <type 'numpy.ndarray'>

In [4]: 'numpy' in str(type(a))
Out[4]: True
Run Code Online (Sandbox Code Playgroud)

(顺便说一下,这个例子在IPython中运行.非常方便交互式使用和快速测试.)

  • 这行得通,但是如果您定义一个名为“ numpygroup”的类型,则会得到误报。另外,如果可以避免的话,取决于类型的字符串表示是一个坏主意,在这种情况下,可以这样做。请查看其模块。 (2认同)

Pie*_* GM 7

这实际上取决于你在寻找什么.

  • 如果你想测试一个序列是否真的是a ndarray,那么a isinstance(..., np.ndarray)可能是最简单的.确保你不在后台重新加载numpy,因为模块可能不同,但除此之外,你应该没问题.MaskedArrays,matrix,recarray是所有子类ndarray,所以你应该设置.
  • 如果你想测试一个标量是否是一个numpy标量,事情变得有点复杂.你可以检查它是否有一个shapedtype属性.您可以将其dtype与基本dtypes 进行比较,您可以在其中找到列表np.core.numerictypes.genericTypeRank.请注意,此列表的元素是字符串,因此您必须执行tested.dtype is np.dtype(an_element_of_the_list)...


Dar*_*ber 7

请注意, 是type(numpy.ndarray)一个type自身,并注意布尔类型和标量类型。如果它不直观或不简单,请不要太沮丧,一开始会很痛苦。

另请参阅: - https://docs.scipy.org/doc/numpy-1.15.1/reference/arrays.dtypes.html - https://github.com/machinalis/mypy-data/tree/master/numpy-米皮

>>> import numpy as np
>>> np.ndarray
<class 'numpy.ndarray'>
>>> type(np.ndarray)
<class 'type'>
>>> a = np.linspace(1,25)
>>> type(a)
<class 'numpy.ndarray'>
>>> type(a) == type(np.ndarray)
False
>>> type(a) == np.ndarray
True
>>> isinstance(a, np.ndarray)
True
Run Code Online (Sandbox Code Playgroud)

布尔值的乐趣:

>>> b = a.astype('int32') == 11
>>> b[0]
False
>>> isinstance(b[0], bool)
False
>>> isinstance(b[0], np.bool)
False
>>> isinstance(b[0], np.bool_)
True
>>> isinstance(b[0], np.bool8)
True
>>> b[0].dtype == np.bool
True
>>> b[0].dtype == bool  # python equivalent
True
Run Code Online (Sandbox Code Playgroud)

标量类型的更多乐趣,请参阅: - https://docs.scipy.org/doc/numpy-1.15.1/reference/arrays.scalars.html#arrays-scalars-built-in

>>> x = np.array([1,], dtype=np.uint64)
>>> x[0].dtype
dtype('uint64')
>>> isinstance(x[0], np.uint64)
True
>>> isinstance(x[0], np.integer)
True  # generic integer
>>> isinstance(x[0], int)
False  # but not a python int in this case

# Try matching the `kind` strings, e.g.
>>> np.dtype('bool').kind                                                                                           
'b'
>>> np.dtype('int64').kind                                                                                          
'i'
>>> np.dtype('float').kind                                                                                          
'f'
>>> np.dtype('half').kind                                                                                           
'f'

# But be weary of matching dtypes
>>> np.integer
<class 'numpy.integer'>
>>> np.dtype(np.integer)
dtype('int64')
>>> x[0].dtype == np.dtype(np.integer)
False

# Down these paths there be dragons:

# the .dtype attribute returns a kind of dtype, not a specific dtype
>>> isinstance(x[0].dtype, np.dtype)
True
>>> isinstance(x[0].dtype, np.uint64)
False  
>>> isinstance(x[0].dtype, np.dtype(np.uint64))
Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError: isinstance() arg 2 must be a type or tuple of types
# yea, don't go there
>>> isinstance(x[0].dtype, np.int_)
False  # again, confusing the .dtype with a specific dtype


# Inequalities can be tricky, although they might
# work sometimes, try to avoid these idioms:

>>> x[0].dtype <= np.dtype(np.uint64)
True
>>> x[0].dtype <= np.dtype(np.float)
True
>>> x[0].dtype <= np.dtype(np.half)
False  # just when things were going well
>>> x[0].dtype <= np.dtype(np.float16)
False  # oh boy
>>> x[0].dtype == np.int
False  # ya, no luck here either
>>> x[0].dtype == np.int_
False  # or here
>>> x[0].dtype == np.uint64
True  # have to end on a good note!
Run Code Online (Sandbox Code Playgroud)