I need to write a function that will determine if an input contains at least one value that is not numeric. If a non-numeric value is detected, I will raise an error (because the calculation should only return a numeric value). The number of measurements of the input array is not known in advance - the function must give the correct value regardless of ndim. As an additional complication, the input can be a single float or numpy.float64 or even something strange, like a zero dimensional array.
The obvious way to solve this problem is to write a recursive function that iterates over each object to be destroyed in the array until it finds iterability. It will apply the numpy.isnan() function for each indestructible object. If at least one non-numeric value is found, the function will immediately return False. Otherwise, if all values ββin iterable are numeric, it will eventually return True.
This works fine, but it's pretty slow, and I expect NumPy to have a much better way to do this. What is an alternative that is faster and more numpyish?
Here is my layout:
def contains_nan( myarray ): """ @param myarray : An n-dimensional array or a single float @type myarray : numpy.ndarray, numpy.array, float @returns: bool Returns true if myarray is numeric or only contains numeric values. Returns false if at least one non-numeric value exists Not-A-Number is given by the numpy.isnan() function. """ return True
python numpy
Salim Fadhley May 26 '09 at 17:43 2009-05-26 17:43
source share