inhouse mean that can handle np.datetime64 or cftime.datetime dtypes
(array, axis=None, skipna=None, **kwargs)
| 756 | |
| 757 | |
| 758 | def 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 | |
| 790 | mean.numeric_only = True # type: ignore[attr-defined] |
searching dependent graphs…