How do I find out if a numpy array contains integers?

后端 未结 5 1131
一个人的身影
一个人的身影 2021-02-03 18:46

I know there is a simple solution to this but can\'t seem to find it at the moment.

Given a numpy array, I need to know if the array contains integers.

Checking

5条回答
  •  情书的邮戳
    2021-02-03 19:34

    Checking for an integer type does not work for floats that are integers, e.g. 4. Better solution is np.equal(np.mod(x, 1), 0), as in:

    >>> 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
    

提交回复
热议问题