This function serves me as a testing-utility to check if the result is really numeric and sometimes as input-validation if there are a lot of operations before I would find out (with an Exception) if it's not-numerical.
But I feel like the .dtype.kind in ...
is too complex. I've written this function a while back and tried using some better approach but I couldn't find any solution that works for python 2.7 and 3.x and different numpy version 1.7+.
The code:
import numpy as np
def is_numeric_array(array):
"""Checks if the dtype of the array is numeric.
Booleans, unsigned integer, signed integer, floats and complex are
considered numeric.
Parameters
----------
array : `numpy.ndarray`-like
The array to check.
Returns
-------
is_numeric : `bool`
True if it is a recognized numerical and False if object or
string.
"""
numerical_dtype_kinds = {'b', # boolean
'u', # unsigned integer
'i', # signed integer
'f', # floats
'c'} # complex
try:
return array.dtype.kind in numerical_dtype_kinds
except AttributeError:
# in case it's not a numpy array it will probably have no dtype.
return np.asarray(array).dtype.kind in numerical_dtype_kinds
and I have the following tests:
def test_not_array():
assert is_numeric_array(1)
assert is_numeric_array(1.)
assert is_numeric_array(1+1j)
assert not is_numeric_array('a')
assert not is_numeric_array(None)
assert is_numeric_array([1, 2, 3])
def test_array():
assert is_numeric_array(np.array(1))
assert is_numeric_array(np.array(1.))
assert is_numeric_array(np.array(1+1j))
assert is_numeric_array(np.array([1]))
assert is_numeric_array(np.array([1.]))
assert is_numeric_array(np.array([1+1j]))
assert not is_numeric_array(np.array('a'))
assert not is_numeric_array(np.array(['a']))
test_not_array()
test_array()