Skip to content

Enable add/sub operations involving a CFTimeIndex and a TimedeltaIndex #2484

Closed
@spencerkclark

Description

@spencerkclark

In [1]: import xarray as xr

In [2]: start_dates = xr.cftime_range('1999-12', periods=12, freq='M')

In [3]: end_dates = start_dates.shift(1, 'M')

In [4]: end_dates - start_dates
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-4-43c24409020b> in <module>()
----> 1 end_dates - start_dates

/Users/spencerclark/xarray-dev/xarray/xarray/coding/cftimeindex.pyc in __sub__(self, other)
    365
    366     def __sub__(self, other):
--> 367         return CFTimeIndex(np.array(self) - other)
    368
    369

TypeError: unsupported operand type(s) for -: 'numpy.ndarray' and 'CFTimeIndex'

Problem description

Subtracting one DatetimeIndex from another produces a TimedeltaIndex:

In [5]: import pandas as pd

In [6]: start_dates = pd.date_range('1999-12', periods=12, freq='M')

In [7]: end_dates = start_dates.shift(1, 'M')

In [8]: end_dates - start_dates
Out[8]:
TimedeltaIndex(['31 days', '29 days', '31 days', '30 days', '31 days',
                '30 days', '31 days', '31 days', '30 days', '31 days',
                '30 days', '31 days'],
               dtype='timedelta64[ns]', freq=None)

This should also be straightforward to enable for CFTimeIndexes and would be useful, for example, in the problem described in #2481 (comment).

Expected Output

In [1]: import xarray as xr

In [2]: start_dates = xr.cftime_range('1999-12', periods=12, freq='M')

In [3]: end_dates = start_dates.shift(1, 'M')

In [4]: end_dates - start_dates
Out[4]:
TimedeltaIndex(['31 days', '29 days', '31 days', '30 days', '31 days',
                '30 days', '31 days', '31 days', '30 days', '31 days',
                '30 days', '31 days'],
               dtype='timedelta64[ns]', freq=None)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions