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

Viewed 29310

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 the dtype per-se is not enough, as there are multiple int dtypes (int8, int16, int32, int64 ...).

6 Answers

Found it in the numpy book! Page 23:

The other types in the hierarchy define particular categories of types. These categories can be useful for testing whether or not the object returned by self.dtype.type is of a particular class (using issubclass).

issubclass(n.dtype('int8').type, n.integer)
>>> True
issubclass(n.dtype('int16').type, n.integer)
>>> True

This also works:

  n.dtype('int8').kind == 'i'

If you are looking to determine if a dtype is integral, then you look at the type hierarchy as the other answers suggest. However, if you want to check floats that may contain integers, you can use (x % 1) == 0, or the ufunc I recently wrote just for the purpose: https://github.com/madphysicist/is_integer_ufunc. After installing, you could run it with

from is_integer_ufunc import is_integer

is_integer(x)

It operates on integers and floating point types equally. The return value is a mask. For integer types, it is always True, while for floats it indicates the elements containing integer values.

Related