🔍 Code Extractor

function is_nan

Maturity: 37

A type-safe utility function that checks whether a given value is NaN (Not a Number), handling arbitrary types without raising exceptions.

File:
/tf/active/vicechatdev/patches/util.py
Lines:
2007 - 2014
Complexity:
simple

Purpose

This function provides a robust way to check for NaN values across different data types. Unlike numpy.isnan() which raises TypeError for non-numeric types, this function gracefully handles any input type by catching exceptions and returning False for types that cannot be NaN. It's particularly useful when working with mixed-type data or when the input type is unknown, making it safer than direct numpy.isnan() calls in generic data processing pipelines.

Source Code

def is_nan(x):
    """
    Checks whether value is NaN on arbitrary types
    """
    try:
        return np.isnan(x)
    except:
        return False

Parameters

Name Type Default Kind
x - - positional_or_keyword

Parameter Details

x: Any value to check for NaN. Can be of any type including numeric types (int, float), numpy arrays, pandas Series, strings, None, or any other Python object. For numeric types, returns True if the value is NaN; for non-numeric types that cannot be NaN, returns False.

Return Value

Returns a boolean value: True if the input is NaN (Not a Number), False otherwise. For types that cannot be NaN (strings, None, lists, etc.), always returns False. For numpy arrays or pandas Series, returns a boolean array/Series with element-wise NaN checks.

Dependencies

  • numpy

Required Imports

import numpy as np

Usage Example

import numpy as np

def is_nan(x):
    try:
        return np.isnan(x)
    except:
        return False

# Example usage:
print(is_nan(float('nan')))  # True
print(is_nan(5.0))  # False
print(is_nan(np.nan))  # True
print(is_nan('string'))  # False
print(is_nan(None))  # False
print(is_nan([1, 2, 3]))  # False
print(is_nan(np.array([1.0, np.nan, 3.0])))  # array([False, True, False])

Best Practices

  • This function uses a bare except clause which catches all exceptions. While this makes it robust, be aware it will silently handle all errors including unexpected ones.
  • For performance-critical code with known numeric types, consider using np.isnan() directly to avoid the try-except overhead.
  • When working with pandas DataFrames or Series, consider using pd.isna() or pd.isnull() which are optimized for pandas objects.
  • The function returns numpy boolean arrays when passed numpy arrays, so handle the return type appropriately in your code.
  • This function treats None as not-NaN (returns False). If you need to check for both NaN and None, use additional checks or pandas' pd.isna() which handles both.
  • Be cautious when using with complex objects - the function will return False for any object that doesn't support np.isnan(), even if conceptually it might represent a missing value.

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function is_float 70.0% similar

    A type-checking utility function that determines whether a given object is a floating-point scalar value, supporting both Python's native float type and NumPy floating-point types.

    From: /tf/active/vicechatdev/patches/util.py
  • function isnumeric 67.4% similar

    Determines whether a given value can be converted to a numeric type (int or float), excluding strings and boolean types.

    From: /tf/active/vicechatdev/patches/util.py
  • function is_number 66.4% similar

    Determines whether an object is a number or behaves like a number, with special handling for numpy types and numeric-like classes.

    From: /tf/active/vicechatdev/patches/util.py
  • function isnat 65.1% similar

    Checks if a value is NaT (Not-a-Time), a special marker for missing or invalid datetime/timedelta values in NumPy and pandas.

    From: /tf/active/vicechatdev/patches/util.py
  • function clean_nan_for_json 63.7% similar

    Recursively traverses nested data structures (dicts, lists) and converts NaN, null, and invalid numeric values to None for safe JSON serialization.

    From: /tf/active/vicechatdev/vice_ai/data_analysis_service.py
← Back to Browse