I'm looking for a way to check for NaN values in Cython code. At the moment, I'm using:
if value != value:
# value is NaN
else:
# value is not NaN
Is there a better way to do this? Is it possible to use a function like Numpy's isnan
?
The math. isnan() method checks whether a value is NaN (Not a Number), or not. This method returns True if the specified value is a NaN, otherwise it returns False.
To check whether a floating point or double number is NaN (Not a Number) in C++, we can use the isnan() function. The isnan() function is present into the cmath library. This function is introduced in C++ version 11.
To check if value at a specific location in Pandas is NaN or not, call numpy. isnan() function with the value passed as argument. If value equals numpy. nan, the expression returns True, else it returns False.
nan is a float value in Python In Python, the float type has nan . You can create nan with float('nan') . Other creation methods are described later. For example, if you read a CSV file in NumPy or pandas, the missing values are represented by nan ( NaN in pandas).
Taken from http://groups.google.com/group/cython-users/msg/1315dd0606389416, you could do this:
cdef extern from "math.h":
bint isnan(double x)
Then you can just use isnan(value)
.
In newer versions of Cython, it is even easier:
from libc.math cimport isnan
If you want to make sure that your code also works on Windows you should better use
cdef extern from "numpy/npy_math.h":
bint npy_isnan(double x)
because on Windows, as far as I know, isnan is called _isnan and is defined in float.h
See also here for example: https://github.com/astropy/astropy/pull/186
If you don't want to introduce numpy you could also insert these precompiler directives into the .c file cython generates:
#if defined(WIN32) || defined(MS_WINDOWS)
#define USEMATH_DEFINES
#define isnan(x) _isnan(x)
#endif
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