代码之家  ›  专栏  ›  技术社区  ›  saffsd

如何确定numpy数组是否包含整数?

  •  46
  • saffsd  · 技术社区  · 16 年前

    我知道有一个简单的解决方案,但目前似乎找不到。

    6 回复  |  直到 16 年前
        1
  •  51
  •   Amanda James saffsd    10 年前

    numpy book !第23页:

    层次结构中的其他类型分为特定的类型类别。 这些类别可用于测试对象是否 self.dtype.type返回的是一个特定的类(使用issubclass)。

    issubclass(n.dtype('int8').type, n.integer)
    >>> True
    issubclass(n.dtype('int16').type, n.integer)
    >>> True
    
        2
  •  26
  •   Peter D    14 年前

    检查整数类型不适用于整数浮点数,例如。 4. 更好的解决方案是 np.equal(np.mod(x, 1), 0) ,如:

    >>> import numpy as np
    >>> def isinteger(x):
    ...     return np.equal(np.mod(x, 1), 0)
    ... 
    >>> foo = np.array([0., 1.5, 1.])
    >>> bar = np.array([-5,  1,  2,  3, -4, -2,  0,  1,  0,  0, -1,  1])
    >>> isinteger(foo)
    array([ True, False,  True], dtype=bool)
    >>> isinteger(bar)
    array([ True,  True,  True,  True,  True,  True,  True,  True,  True,
        True,  True,  True], dtype=bool)
    >>> isinteger(1.5)
    False
    >>> isinteger(1.)
    True
    >>> isinteger(1)
    True
    
        3
  •  9
  •   Dan Dan    16 年前

    这也有效:

      n.dtype('int8').kind == 'i'
    
        4
  •  6
  •   funk    10 年前

    Numpy的issubtype()函数可以按如下方式使用:

    import numpy as np
    
    size=(3,3)
    A = np.random.randint(0, 255, size)
    B = np.random.random(size)
    
    print 'Array A:\n',  A
    print 'Integers:', np.issubdtype(A[0,0], int)
    print 'Floats:', np.issubdtype(A[0,0], float)
    
    print '\nArray B:\n',  B
    print 'Integers:', np.issubdtype(B[0,0], int)
    print 'Floats:', np.issubdtype(B[0,0], float)
    

    结果:

    Array A:
    [[  9 224  33]
     [210 117  83]
     [206 139  60]]
    Integers: True
    Floats: False
    
    Array B:
    [[ 0.54221849  0.96021118  0.72322367]
     [ 0.02207826  0.55162813  0.52167972]
     [ 0.74106348  0.72457807  0.9705301 ]]
    Integers: False
    Floats: True
    

        5
  •  3
  •   CharlesB Craig McQueen    6 年前

    the accepted answer from 2009 a new and enhanced solution 截至2014年9月发布的Numpy v0.19:

    所有数值numpy类型现在都已在类型层次结构中注册 在python数字模块中。

    这允许检查 dtype 反对Python Numeric abstract base classes .

    issubclass(np.dtype('int32').type, numbers.Integral)
    

    您可以进行测试 numbers.Complex , numbers.Real numbers.Integral .