How to check if all elements of a numpy array have integer values?

Viewed 2616

As the title says, it is not about type of elements. I need to be sure that the values of elements are integers, i.e.

np.array([1, 2, 3])
np.array([1., 2.0, 9/3])

must both give [True, True, True] after the 'Are they integers?'-checking.

Is there a clean and pythonic/numpyic way of doing this?

I've tried some many-lines-combinations such as:

isinstance(x, (int, np.integer)) 
#or
(1.0).is_integer()

but they are cumbersome and ugly.

3 Answers

What I use is this quantity % int(quantity) == 0

Here is a oneliner using is_integer():

>>> x = np.array([1., 2.0, 9/3])
>>> all([i.is_integer() for i in x])
True

One More Way:

>>> x = np.array([1.,2.0,9/3])
>>> [not (i%1) for i in x]
[True, True, True]
Related