如何在python中识别numpy类型?

如何在python中识别numpy类型?,python,numpy,duck-typing,dynamic-typing,Python,Numpy,Duck Typing,Dynamic Typing,如何可靠地确定对象是否具有numpy类型 我意识到这个问题违背了duck类型的原理,但我的想法是确保函数(使用scipy和numpy)永远不会返回numpy类型,除非用numpy类型调用它。但我认为确定一个对象是否具有numpy类型的一般问题与原始问题的距离足够远,它们应该分开。我提出的解决方案是: isinstance(y, (np.ndarray, np.generic) ) 但是,所有numpy类型都保证是np.ndarray或np.generic,这可能不是版本健壮的。要获取类型,请使

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


我意识到这个问题违背了duck类型的原理,但我的想法是确保函数(使用scipy和numpy)永远不会返回numpy类型,除非用numpy类型调用它。但我认为确定一个对象是否具有numpy类型的一般问题与原始问题的距离足够远,它们应该分开。

我提出的解决方案是:

isinstance(y, (np.ndarray, np.generic) )

但是,所有numpy类型都保证是
np.ndarray
np.generic
,这可能不是版本健壮的。

要获取类型,请使用内置的
type
函数。使用操作符中的
,您可以通过检查该类型是否包含字符串
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
[1]中的
:将numpy作为np导入
[2]中:a=np.array([1,2,3])
在[3]中:类型(a)
出[3]:
[4]中:str中的“numpy”(类型(a))
Out[4]:正确

(顺便说一句,这个示例是在中运行的。对于交互式使用和快速测试来说非常方便。)

使用内置的
类型
函数来获取类型,然后您可以使用
\uuu模块
属性来找出它的定义位置:

>>> 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
>>将numpy作为np导入
a=np.array([1,2,3])
>>>类型(a)
>>>类型(a).\u模块__
“努比”
>>>类型(a)。\uuuuu模块\uuuu==np.\uuuu名称__
真的

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

  • 如果您想测试序列是否实际上是
    ndarray
    ,那么
    isinstance(…,np.ndarray)
    可能是最简单的。请确保不要在后台重新加载numpy,因为模块可能不同,否则应该可以
    maskedarray
    matrix
    recarray
    都是
    ndarray
    的子类,因此应该设置
  • 如果你想测试一个标量是否是numpy标量,事情会变得复杂一些。您可以检查它是否具有
    shape
    dtype
    属性。您可以将其
    dtype
    与基本dtype进行比较,您可以在
    np.core.numerictypes.genericTypeRank
    中找到基本dtype的列表。请注意,此列表中的元素是字符串,因此您必须进行
    测试。dtype是np.dtype(列表中的元素)

    • 这是一个老问题,但我用一个例子给出了一个明确的答案。我有同样的问题,没有找到一个明确的答案。关键是确保导入了
      numpy
      ,然后运行
      isinstance
      bool。虽然这看起来很简单,但是如果您正在跨不同的数据类型进行一些计算,那么在开始一些numpy矢量化操作之前,这个小检查可以作为一个快速测试

      ##################
      #重要的部分!
      ##################
      将numpy作为np导入
      ####################
      #玩具阵列演示
      ####################
      arr=np.asarray(范围(1100,2))
      ########################
      #实例检查
      ######################## 
      isinstance(arr,np.ndarray)
      
      请注意
      类型(numpy.ndarray)
      本身就是
      类型,请注意布尔类型和标量类型。不要太气馁,如果这不是直观的或容易的,这是一个痛苦的开始

      另见: - -

      >>将numpy作为np导入
      >>>np.ndarray
      >>>类型(np.ndarray)
      >>>a=np.linspace(1,25)
      >>>类型(a)
      >>>类型(a)=类型(np.Ndaray)
      假的
      >>>类型(a)==np.ndarray
      真的
      >>>isinstance(a,np.ndarray)
      真的
      
      布尔人的乐趣:

      >>> 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
      
      有关标量类型的更多乐趣,请参见: -

      >x=np.array([1,],dtype=np.uint64)
      >>>x[0]。数据类型
      数据类型('uint64')
      >>>isinstance(x[0],np.uint64)
      真的
      >>>isinstance(x[0],np.整数)
      真#泛型整数
      >>>isinstance(x[0],int)
      False#但在本例中不是python int
      #尝试匹配'kind'字符串,例如。
      >>>np.dtype('bool').kind
      “b”
      >>>np.dtype('int64').kind
      “我很高兴
      >>>np.dtype('float').kind
      “f”
      >>>np.dtype('half').kind
      “f”
      #但对匹配的数据类型感到厌倦
      >>>np.integer
      >>>np.dtype(np.integer)
      数据类型('int64')
      >>>x[0].dtype==np.dtype(np.integer)
      假的
      #沿着这些路径,有龙:
      #.dtype属性返回一种数据类型,而不是特定的数据类型
      >>>isinstance(x[0].dtype,np.dtype)
      真的
      >>>isinstance(x[0].数据类型,np.uint64)
      假的
      >>>isinstance(x[0].dtype,np.dtype(np.uint64))
      回溯(最近一次呼叫最后一次):
      文件“”,第1行,在
      TypeError:isinstance()arg 2必须是类型或类型的元组
      #是的,不要去那里
      >>>isinstance(x[0].dtype,np.int\ux)
      False#再次,将.dtype与特定的dtype混淆
      #不平等可能是棘手的,尽管它们可能是
      #有时工作,尽量避免使用以下习惯用语:
      >>>x[0]。dtype>>x[0]。dtype>>x[0]。dtype>>x[0]。dtype>>x[0]。dtype==np.int
      错#是的,这里也没有运气
      >>>x[0]。dtype==np.int_
      错#还是在这里
      >>>x[0]。数据类型==np.uint64
      没错,必须以一个好的音符结束!
      
      这是可行的,但如果您定义一个名为“numpygroup”的类型,您将得到误报。此外,如果可以避免使用类型的字符串表示,那么依赖类型的字符串表示是一个坏主意,在本例中,您可以这样做。相反,看看它的模块。使用该模块确实是一个更好的解决方案。Regex可以used@Omkaar.K正则表达式可以用来做什么?要以稍微复杂一点的方式执行完全相同的检查?@abamert“Could”是我所说的,对于这样的简单任务,regex看起来也可能很复杂,但它对于大型字符串处理任务非常有用,因此学习它不是一个坏主意。我想你已经知道了,因为你的投资组合把你描绘成一个高级程序员
      >>> 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!