Skip to content

ENH: implement DateOffset + np.datetime64 array #47014

Open
@hottwaj

Description

@hottwaj

Is your feature request related to a problem?

DateOffset + a numpy array of type datetime64 does not work, see examples at the end of this post

Describe the solution you'd like

can __add__ or __radd__ of DateOffset be changed to implement addition to datetime64 array?

API breaking implications

I am not the right person to comment, but seems unlikely to have an impact on existing API if it can be done at all

Describe alternatives you've considered

Sorry, not thought of alternatives so far

Code example

>>> import pandas
>>> import numpy
>>> dates = pandas.Series([pandas.Timestamp(2021, 1, 1) + pandas.Timedelta(days=d) for d in range(1000)])
>>> offset = pandas.offsets.MonthEnd()

>>> # adding a pandas Timestamp series to an offset obviously works
>>> dates + offset
0     2021-01-31
1     2021-01-31
         ...    
998   2023-09-30
999   2023-09-30
Length: 1000, dtype: datetime64[ns]

>>> # adding the underlying numpy datetime64 values does not work 
>>> offset + dates.values
---------------------------------------------------------------------------
UFuncTypeError                            Traceback (most recent call last)
----> 1 offset + dates.values

UFuncTypeError: ufunc 'add' cannot use operands with types dtype('O') and dtype('<M8[ns]')

>>> # slightly different error if we swap the order of the two variables
>>> dates.values + offset
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
----> 1 dates.values + offset

TypeError: Concatenation operation is not implemented for NumPy arrays, use np.concatenate() instead. Please do not rely on this error; it may not be given on all Python implementations.

>>> # the desired result can be achieved by using DateOffset._apply_array() and casting to M8[ns]
>>> offset._apply_array(dates.values).astype('M8[ns]')
array(['2021-01-31T00:00:00.000000000', '2021-01-31T00:00:00.000000000',
       '2021-01-31T00:00:00.000000000', '2021-01-31T00:00:00.000000000',
       '2021-01-31T00:00:00.000000000', '2021-01-31T00:00:00.000000000',
       '2021-01-31T00:00:00.000000000', '2021-01-31T00:00:00.000000000',
       etc])

Metadata

Metadata

Assignees

No one assigned

    Labels

    Compatpandas objects compatability with Numpy or Python functionsEnhancementFrequencyDateOffsetsNumeric OperationsArithmetic, Comparison, and Logical operations

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions