Skip to main content

numpy_utils

Utility functions for interacting with numpy.

Module

Functions

check_for_compatible_lengths

def check_for_compatible_lengths(    a: np.ndarray | list[np.ndarray] | list[T],    b: np.ndarray | list[np.ndarray] | list[T],    a_name: str = 'the first arg',    b_name: str = 'the second arg',)> None:

Checks if two numpy-related collections are compatible lengths.

Compatible lengths here means they are equal in size in the first or second dimension.

Raises

  • ValueError: if the lengths are incompatible

json_safe

def json_safe(value: Any)> Any:

Recursively convert numpy scalars/arrays in value to native types.

The stdlib json encoder accepts numpy.floating (a float subclass) but rejects numpy.integer (not an int subclass) and numpy.ndarray. Payloads built from pandas rows can carry either, so callers writing to JSON columns route the payload through this to stay correct by construction rather than relying on each value happening to be float-typed.

Non-finite floats (NaN, inf, -inf) are mapped to None (JSON null): they are not valid standard JSON, so persisting them into a JSON column would emit non-standard tokens that break strict readers and other DB backends. null is the portable representation of an absent/undefined value.

Arguments

  • value: A JSON-bound value, or a (possibly nested) dict/list/array of them.

Returns The same structure with any numpy scalars/arrays replaced by native Python types and any non-finite float replaced by None.