Skip to content

pyhiperta.utils.nanify

Transform values to NaN.

Functions:

Name Description
nanify

Set a or values of a to np.nan where condition is true.

nanify

nanify(a, condition)

Set a or values of a to np.nan where condition is true.

a can either be a number, then nanify returns np.nan if condition is true, or an array, in which case nanify returns the array with the values where condition is true set to np.nan. This function main purpose is to provide a convinient way to perform a[condition] = np.nan even when a is a single number and not an array.

Parameters:

Name Type Description Default
a scalar or ndarray

The value to convert to np.nan is condition is true.

required
condition bool or ndarray

The boolean(s) controlling where to set values to np.nan. If an array it typically is a numpy condition array, see examples.

required

Returns:

Type Description
np.nan if a is a scalar, otherwise `a` after `a[condition] = np.nan`.

Examples:

>>> a = 12
>>> nanify(a, a < 13)
np.float32(nan)
>>> a = np.array([1.0, 2.0, 3.0])
>>> nanify(a, a < 2)
array([nan,  2.,  3.])
Source code in src/pyhiperta/utils/nanify.py
def nanify(a, condition):
    """Set a or values of a to np.nan where `condition` is true.

    `a` can either be a number, then `nanify` returns np.nan if condition is true, or an array,
    in which case `nanify` returns the array with the values where condition is true set to np.nan.
    This function main purpose is to provide a convinient way to perform `a[condition] = np.nan`
    even when `a` is a single number and not an array.

    Parameters
    ----------
    a : np.scalar or np.ndarray
        The value to convert to np.nan is condition is true.
    condition : bool or np.ndarray
        The boolean(s) controlling where to set values to np.nan. If an array it typically is a
        numpy condition array, see examples.

    Returns
    -------
    np.nan if a is a scalar, otherwise `a` after `a[condition] = np.nan`.

    Examples
    --------
    >>> a = 12
    >>> nanify(a, a < 13)
    np.float32(nan)
    >>> a = np.array([1.0, 2.0, 3.0])
    >>> nanify(a, a < 2)
    array([nan,  2.,  3.])
    """
    if np.isscalar(a):
        if condition:
            return np.float32(np.nan)  # this is subscriptable, while np.nan[..., np.newaxis] raises an exception!
        return a
    a[condition] = np.nan
    return a