Ejemplo n.º 1
0
 def test_astype_object(self):
     tdi = pd.TimedeltaIndex(['1 Day', '3 Hours'])
     arr = TimedeltaArrayMixin(tdi)
     asobj = arr.astype('O')
     assert isinstance(asobj, np.ndarray)
     assert asobj.dtype == 'O'
     assert list(asobj) == list(tdi)
Ejemplo n.º 2
0
 def test_astype_object(self):
     tdi = pd.TimedeltaIndex(['1 Day', '3 Hours'])
     arr = TimedeltaArrayMixin(tdi)
     asobj = arr.astype('O')
     assert isinstance(asobj, np.ndarray)
     assert asobj.dtype == 'O'
     assert list(asobj) == list(tdi)
Ejemplo n.º 3
0
 def __rtruediv__(self, other):
     oth = other
     if isinstance(other, Index):
         # TimedeltaArray defers, so we need to unwrap
         oth = other._values
     result = TimedeltaArray.__rtruediv__(self, oth)
     return wrap_arithmetic_op(self, other, result)
Ejemplo n.º 4
0
 def __rtruediv__(self, other):
     oth = other
     if isinstance(other, Index):
         # TimedeltaArray defers, so we need to unwrap
         oth = other._values
     result = TimedeltaArray.__rtruediv__(self, oth)
     return wrap_arithmetic_op(self, other, result)
Ejemplo n.º 5
0
    def _add_delta(self, delta):
        """
        Add a timedelta-like, DateOffset, or TimedeltaIndex-like object
        to self.

        Parameters
        ----------
        delta : {timedelta, np.timedelta64, DateOffset,
                 TimedelaIndex, ndarray[timedelta64]}

        Returns
        -------
        result : same type as self

        Notes
        -----
        The result's name is set outside of _add_delta by the calling
        method (__add__ or __sub__)
        """
        from pandas.core.arrays.timedeltas import TimedeltaArrayMixin

        if isinstance(delta, (Tick, timedelta, np.timedelta64)):
            new_values = self._add_delta_td(delta)
        elif is_timedelta64_dtype(delta):
            if not isinstance(delta, TimedeltaArrayMixin):
                delta = TimedeltaArrayMixin(delta)
            new_values = self._add_delta_tdi(delta)
        else:
            new_values = self.astype('O') + delta

        tz = 'UTC' if self.tz is not None else None
        result = type(self)(new_values, tz=tz, freq='infer')
        if self.tz is not None and self.tz is not utc:
            result = result.tz_convert(self.tz)
        return result
Ejemplo n.º 6
0
    def __new__(cls,
                data=None,
                unit=None,
                freq=None,
                start=None,
                end=None,
                periods=None,
                closed=None,
                dtype=_TD_DTYPE,
                copy=False,
                name=None,
                verify_integrity=None):

        if verify_integrity is not None:
            warnings.warn(
                "The 'verify_integrity' argument is deprecated, "
                "will be removed in a future version.",
                FutureWarning,
                stacklevel=2)
        else:
            verify_integrity = True

        if data is None:
            freq, freq_infer = dtl.maybe_infer_freq(freq)
            warnings.warn(
                "Creating a TimedeltaIndex by passing range "
                "endpoints is deprecated.  Use "
                "`pandas.timedelta_range` instead.",
                FutureWarning,
                stacklevel=2)
            tdarr = TimedeltaArray._generate_range(start,
                                                   end,
                                                   periods,
                                                   freq,
                                                   closed=closed)
            return cls(tdarr, name=name)

        if is_scalar(data):
            raise TypeError(
                '{cls}() must be called with a '
                'collection of some kind, {data} was passed'.format(
                    cls=cls.__name__, data=repr(data)))

        if isinstance(data, TimedeltaIndex) and freq is None and name is None:
            if copy:
                return data.copy()
            else:
                return data._shallow_copy()

        # - Cases checked above all return/raise before reaching here - #

        result = cls._from_sequence(data,
                                    freq=freq,
                                    unit=unit,
                                    dtype=dtype,
                                    copy=copy)
        result.name = name
        return result
    def test_from_tdi(self):
        tdi = pd.TimedeltaIndex(['1 Day', '3 Hours'])
        arr = TimedeltaArrayMixin(tdi)
        assert list(arr) == list(tdi)

        # Check that Index.__new__ knows what to do with TimedeltaArray
        tdi2 = pd.Index(arr)
        assert isinstance(tdi2, pd.TimedeltaIndex)
        assert list(tdi2) == list(arr)
Ejemplo n.º 8
0
    def _simple_new(cls, values, name=None, freq=None, dtype=_TD_DTYPE):
        # `dtype` is passed by _shallow_copy in corner cases, should always
        #  be timedelta64[ns] if present
        if not isinstance(values, TimedeltaArray):
            values = TimedeltaArray._simple_new(values, dtype=dtype, freq=freq)
        assert isinstance(values, TimedeltaArray), type(values)
        assert dtype == _TD_DTYPE, dtype
        assert values.dtype == 'm8[ns]', values.dtype

        freq = to_offset(freq)
        tdarr = TimedeltaArray._simple_new(values, freq=freq)
        result = object.__new__(cls)
        result._data = tdarr
        result.name = name
        # For groupby perf. See note in indexes/base about _index_data
        result._index_data = tdarr._data

        result._reset_identity()
        return result
Ejemplo n.º 9
0
    def __new__(cls, data=None, unit=None, freq=None, start=None, end=None,
                periods=None, closed=None, dtype=_TD_DTYPE, copy=False,
                name=None, verify_integrity=None):

        if verify_integrity is not None:
            warnings.warn("The 'verify_integrity' argument is deprecated, "
                          "will be removed in a future version.",
                          FutureWarning, stacklevel=2)
        else:
            verify_integrity = True

        if data is None:
            freq, freq_infer = dtl.maybe_infer_freq(freq)
            warnings.warn("Creating a TimedeltaIndex by passing range "
                          "endpoints is deprecated.  Use "
                          "`pandas.timedelta_range` instead.",
                          FutureWarning, stacklevel=2)
            result = TimedeltaArray._generate_range(start, end, periods, freq,
                                                    closed=closed)
            return cls._simple_new(result._data, freq=freq, name=name)

        if is_scalar(data):
            raise TypeError('{cls}() must be called with a '
                            'collection of some kind, {data} was passed'
                            .format(cls=cls.__name__, data=repr(data)))

        if isinstance(data, TimedeltaIndex) and freq is None and name is None:
            if copy:
                return data.copy()
            else:
                return data._shallow_copy()

        # - Cases checked above all return/raise before reaching here - #

        tdarr = TimedeltaArray._from_sequence(data, freq=freq, unit=unit,
                                              dtype=dtype, copy=copy)
        return cls._simple_new(tdarr._data, freq=tdarr.freq, name=name)
Ejemplo n.º 10
0
    def _simple_new(cls, values, name=None, freq=None, dtype=_TD_DTYPE):
        # `dtype` is passed by _shallow_copy in corner cases, should always
        #  be timedelta64[ns] if present
        assert dtype == _TD_DTYPE

        assert isinstance(values, np.ndarray), type(values)
        if values.dtype == 'i8':
            values = values.view('m8[ns]')
        assert values.dtype == 'm8[ns]', values.dtype

        freq = to_offset(freq)
        tdarr = TimedeltaArray._simple_new(values, freq=freq)
        result = object.__new__(cls)
        result._data = tdarr._data
        result._freq = tdarr._freq
        result.name = name
        # For groupby perf. See note in indexes/base about _index_data
        result._index_data = result._data
        result._reset_identity()
        return result
Ejemplo n.º 11
0
    def _simple_new(cls, values, name=None, freq=None, dtype=_TD_DTYPE):
        # `dtype` is passed by _shallow_copy in corner cases, should always
        #  be timedelta64[ns] if present
        assert dtype == _TD_DTYPE

        assert isinstance(values, np.ndarray), type(values)
        if values.dtype == 'i8':
            values = values.view('m8[ns]')
        assert values.dtype == 'm8[ns]', values.dtype

        freq = to_offset(freq)
        tdarr = TimedeltaArray._simple_new(values, freq=freq)
        result = object.__new__(cls)
        result._eadata = tdarr
        result.name = name
        # For groupby perf. See note in indexes/base about _index_data
        # TODO: make sure this is updated correctly if edited
        result._index_data = tdarr._data

        result._reset_identity()
        return result
Ejemplo n.º 12
0
 def _evaluate_with_timedelta_like(self, other, op):
     result = TimedeltaArrayMixin._evaluate_with_timedelta_like(self, other,
                                                                op)
     return wrap_arithmetic_op(self, other, result)
Ejemplo n.º 13
0
 def total_seconds(self):
     result = TimedeltaArrayMixin.total_seconds(self)
     return Index(result, name=self.name)
Ejemplo n.º 14
0
def timedelta_range(start=None, end=None, periods=None, freq=None,
                    name=None, closed=None):
    """
    Return a fixed frequency TimedeltaIndex, with day as the default
    frequency

    Parameters
    ----------
    start : string or timedelta-like, default None
        Left bound for generating timedeltas
    end : string or timedelta-like, default None
        Right bound for generating timedeltas
    periods : integer, default None
        Number of periods to generate
    freq : string or DateOffset, default 'D'
        Frequency strings can have multiples, e.g. '5H'
    name : string, default None
        Name of the resulting TimedeltaIndex
    closed : string, default None
        Make the interval closed with respect to the given frequency to
        the 'left', 'right', or both sides (None)

    Returns
    -------
    rng : TimedeltaIndex

    Notes
    -----
    Of the four parameters ``start``, ``end``, ``periods``, and ``freq``,
    exactly three must be specified. If ``freq`` is omitted, the resulting
    ``TimedeltaIndex`` will have ``periods`` linearly spaced elements between
    ``start`` and ``end`` (closed on both sides).

    To learn more about the frequency strings, please see `this link
    <http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases>`__.

    Examples
    --------

    >>> pd.timedelta_range(start='1 day', periods=4)
    TimedeltaIndex(['1 days', '2 days', '3 days', '4 days'],
                   dtype='timedelta64[ns]', freq='D')

    The ``closed`` parameter specifies which endpoint is included.  The default
    behavior is to include both endpoints.

    >>> pd.timedelta_range(start='1 day', periods=4, closed='right')
    TimedeltaIndex(['2 days', '3 days', '4 days'],
                   dtype='timedelta64[ns]', freq='D')

    The ``freq`` parameter specifies the frequency of the TimedeltaIndex.
    Only fixed frequencies can be passed, non-fixed frequencies such as
    'M' (month end) will raise.

    >>> pd.timedelta_range(start='1 day', end='2 days', freq='6H')
    TimedeltaIndex(['1 days 00:00:00', '1 days 06:00:00', '1 days 12:00:00',
                    '1 days 18:00:00', '2 days 00:00:00'],
                   dtype='timedelta64[ns]', freq='6H')

    Specify ``start``, ``end``, and ``periods``; the frequency is generated
    automatically (linearly spaced).

    >>> pd.timedelta_range(start='1 day', end='5 days', periods=4)
    TimedeltaIndex(['1 days 00:00:00', '2 days 08:00:00', '3 days 16:00:00',
                '5 days 00:00:00'],
               dtype='timedelta64[ns]', freq=None)
    """
    if freq is None and com._any_none(periods, start, end):
        freq = 'D'

    freq, freq_infer = dtl.maybe_infer_freq(freq)
    tdarr = TimedeltaArray._generate_range(start, end, periods, freq,
                                           closed=closed)
    return TimedeltaIndex._simple_new(tdarr._data, freq=tdarr.freq, name=name)
Ejemplo n.º 15
0
 def _evaluate_with_timedelta_like(self, other, op):
     result = TimedeltaArrayMixin._evaluate_with_timedelta_like(
         self, other, op)
     if result is NotImplemented:
         return NotImplemented
     return Index(result, name=self.name, copy=False)
Ejemplo n.º 16
0
 def _eadata(self):
     return TimedeltaArray._simple_new(self._data, freq=self.freq)
Ejemplo n.º 17
0
 def total_seconds(self):
     result = TimedeltaArrayMixin.total_seconds(self)
     return Index(result, name=self.name)
Ejemplo n.º 18
0
 def _eadata(self):
     return TimedeltaArray._simple_new(self._data, freq=self.freq)
Ejemplo n.º 19
0
def timedelta_range(start=None, end=None, periods=None, freq=None,
                    name=None, closed=None):
    """
    Return a fixed frequency TimedeltaIndex, with day as the default
    frequency

    Parameters
    ----------
    start : string or timedelta-like, default None
        Left bound for generating timedeltas
    end : string or timedelta-like, default None
        Right bound for generating timedeltas
    periods : integer, default None
        Number of periods to generate
    freq : string or DateOffset, default 'D'
        Frequency strings can have multiples, e.g. '5H'
    name : string, default None
        Name of the resulting TimedeltaIndex
    closed : string, default None
        Make the interval closed with respect to the given frequency to
        the 'left', 'right', or both sides (None)

    Returns
    -------
    rng : TimedeltaIndex

    Notes
    -----
    Of the four parameters ``start``, ``end``, ``periods``, and ``freq``,
    exactly three must be specified. If ``freq`` is omitted, the resulting
    ``TimedeltaIndex`` will have ``periods`` linearly spaced elements between
    ``start`` and ``end`` (closed on both sides).

    To learn more about the frequency strings, please see `this link
    <http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases>`__.

    Examples
    --------

    >>> pd.timedelta_range(start='1 day', periods=4)
    TimedeltaIndex(['1 days', '2 days', '3 days', '4 days'],
                   dtype='timedelta64[ns]', freq='D')

    The ``closed`` parameter specifies which endpoint is included.  The default
    behavior is to include both endpoints.

    >>> pd.timedelta_range(start='1 day', periods=4, closed='right')
    TimedeltaIndex(['2 days', '3 days', '4 days'],
                   dtype='timedelta64[ns]', freq='D')

    The ``freq`` parameter specifies the frequency of the TimedeltaIndex.
    Only fixed frequencies can be passed, non-fixed frequencies such as
    'M' (month end) will raise.

    >>> pd.timedelta_range(start='1 day', end='2 days', freq='6H')
    TimedeltaIndex(['1 days 00:00:00', '1 days 06:00:00', '1 days 12:00:00',
                    '1 days 18:00:00', '2 days 00:00:00'],
                   dtype='timedelta64[ns]', freq='6H')

    Specify ``start``, ``end``, and ``periods``; the frequency is generated
    automatically (linearly spaced).

    >>> pd.timedelta_range(start='1 day', end='5 days', periods=4)
    TimedeltaIndex(['1 days 00:00:00', '2 days 08:00:00', '3 days 16:00:00',
                '5 days 00:00:00'],
               dtype='timedelta64[ns]', freq=None)
    """
    if freq is None and com._any_none(periods, start, end):
        freq = 'D'

    freq, freq_infer = dtl.maybe_infer_freq(freq)
    tdarr = TimedeltaArray._generate_range(start, end, periods, freq,
                                           closed=closed)
    return TimedeltaIndex._simple_new(tdarr._data, freq=tdarr.freq, name=name)
Ejemplo n.º 20
0
 def test_from_tdi(self):
     tdi = pd.TimedeltaIndex(['1 Day', '3 Hours'])
     arr = TimedeltaArrayMixin(tdi)
     assert list(arr) == list(tdi)
Ejemplo n.º 21
0
 def _evaluate_with_timedelta_like(self, other, op):
     result = TimedeltaArray._evaluate_with_timedelta_like(self, other, op)
     return wrap_arithmetic_op(self, other, result)
Ejemplo n.º 22
0
 def _evaluate_with_timedelta_like(self, other, op):
     result = TimedeltaArrayMixin._evaluate_with_timedelta_like(self, other,
                                                                op)
     if result is NotImplemented:
         return NotImplemented
     return Index(result, name=self.name, copy=False)