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 ...).
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“.
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.
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 ).
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With