Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

numpy

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

like image 872
saffsd Avatar asked Jun 01 '09 12:06

saffsd


People also ask

How do you check if a number is in a NumPy array?

Using Numpy array, we can easily find whether specific values are present or not. For this purpose, we use the “in” operator. “in” operator is used to check whether certain element and values are present in a given sequence and hence return Boolean values 'True” and “False“.

How can we find type of NumPy arrays?

The astype() function creates a copy of the array, and allows you to specify the data type as a parameter. The data type can be specified using a string, like 'f' for float, 'i' for integer etc. or you can use the data type directly like float for float and int for integer.

How do you check if a variable is a NumPy array?

Checking correct variable type. To test that F is an array, we can use isinstance(F, np. ndarray) ( ndarray is the name of the array type in numpy ).

Can NumPy arrays contain strings and numbers?

The NumPy array, formally called ndarray in NumPy documentation, is similar to a list but where all the elements of the list are of the same type. The elements of a NumPy array, or simply an array, are usually numbers, but can also be boolians, strings, or other objects.


2 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
like image 120
saffsd Avatar answered Oct 12 '22 12:10

saffsd


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
like image 36
Peter D Avatar answered Oct 12 '22 12:10

Peter D