Skip to content

Commit

Permalink
fix empty cftimindex
Browse files Browse the repository at this point in the history
  • Loading branch information
mathause committed Jan 12, 2024
1 parent 0354d17 commit 769a872
Showing 1 changed file with 19 additions and 2 deletions.
21 changes: 19 additions & 2 deletions xarray/coding/cftimeindex.py
Original file line number Diff line number Diff line change
Expand Up @@ -272,8 +272,8 @@ def format_attrs(index, separator=", "):
attrs = {
"dtype": f"'{index.dtype}'",
"length": f"{len(index)}",
"calendar": f"'{index.calendar}'" if len(index) else None,
"freq": f"'{index.freq}'" if len(index) >= 3 else None,
"calendar": f"'{index.calendar}'",
"freq": f"'{index.freq}'",
}

attrs_str = [f"{k}={v}" for k, v in attrs.items()]
Expand Down Expand Up @@ -630,6 +630,10 @@ def to_datetimeindex(self, unsafe=False):
>>> times.to_datetimeindex()
DatetimeIndex(['2000-01-01', '2000-01-02'], dtype='datetime64[ns]', freq=None)
"""

if not self._data.size:
return pd.Index([], dtype="datetime64[ns]")

nptimes = cftime_to_nptime(self)
calendar = infer_calendar_name(self)
if calendar not in _STANDARD_CALENDARS and not unsafe:
Expand Down Expand Up @@ -679,6 +683,9 @@ def asi8(self):
"""Convert to integers with units of microseconds since 1970-01-01."""
from xarray.core.resample_cftime import exact_cftime_datetime_difference

if not self._data.size:
return np.array([], dtype=np.int64)

epoch = self.date_type(1970, 1, 1)
return np.array(
[
Expand All @@ -693,19 +700,29 @@ def calendar(self):
"""The calendar used by the datetimes in the index."""
from xarray.coding.times import infer_calendar_name

if not self._data.size:
return None

return infer_calendar_name(self)

@property
def freq(self):
"""The frequency used by the dates in the index."""
from xarray.coding.frequencies import infer_freq

# min 3 elemtents required to determine freq
if self._data.size < 3:
return None

return infer_freq(self)

def _round_via_method(self, freq, method):
"""Round dates using a specified method."""
from xarray.coding.cftime_offsets import CFTIME_TICKS, to_offset

if not self._data.size:
return CFTimeIndex(np.array(self))

offset = to_offset(freq)
if not isinstance(offset, CFTIME_TICKS):
raise ValueError(f"{offset} is a non-fixed frequency")
Expand Down

0 comments on commit 769a872

Please sign in to comment.