MCPcopy
hub / github.com/pydata/xarray / mean

Function mean

xarray/core/duck_array_ops.py:758–787  ·  view source on GitHub ↗

inhouse mean that can handle np.datetime64 or cftime.datetime dtypes

(array, axis=None, skipna=None, **kwargs)

Source from the content-addressed store, hash-verified

756
757
758def mean(array, axis=None, skipna=None, **kwargs):
759 """inhouse mean that can handle np.datetime64 or cftime.datetime
760 dtypes"""
761 from xarray.core.common import _contains_cftime_datetimes
762
763 array = asarray(array)
764 if dtypes.is_datetime_like(array.dtype):
765 dmin = _datetime_nanreduce(array, min).astype("datetime64[Y]").astype(int)
766 dmax = _datetime_nanreduce(array, max).astype("datetime64[Y]").astype(int)
767 offset = (
768 np.array((dmin + dmax) // 2).astype("datetime64[Y]").astype(array.dtype)
769 )
770 # From version 2025.01.2 xarray uses np.datetime64[unit], where unit
771 # is one of "s", "ms", "us", "ns".
772 # To not have to worry about the resolution, we just convert the output
773 # to "timedelta64" (without unit) and let the dtype of offset take precedence.
774 # This is fully backwards compatible with datetime64[ns].
775 return (
776 _mean(
777 datetime_to_numeric(array, offset), axis=axis, skipna=skipna, **kwargs
778 ).astype("timedelta64")
779 + offset
780 )
781 elif _contains_cftime_datetimes(array):
782 offset = min(array)
783 timedeltas = datetime_to_numeric(array, offset, datetime_unit="us")
784 mean_timedeltas = _mean(timedeltas, axis=axis, skipna=skipna, **kwargs)
785 return _to_pytimedelta(mean_timedeltas, unit="us") + offset
786 else:
787 return _mean(array, axis=axis, skipna=skipna, **kwargs)
788
789
790mean.numeric_only = True # type: ignore[attr-defined]

Callers 1

test_all_nan_arraysMethod · 0.90

Calls 6

asarrayFunction · 0.85
_datetime_nanreduceFunction · 0.85
datetime_to_numericFunction · 0.85
_to_pytimedeltaFunction · 0.85
astypeMethod · 0.45

Tested by 1

test_all_nan_arraysMethod · 0.72

Used in the wild real call sites across dependent graphs

searching dependent graphs…