Python pandas.TimedeltaIndex() Examples

The following are 30 code examples of pandas.TimedeltaIndex(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pandas , or try the search function .
Example #1
Source File: test_coercion.py    From recruit with Apache License 2.0 7 votes vote down vote up
def test_insert_index_timedelta64(self):
        obj = pd.TimedeltaIndex(['1 day', '2 day', '3 day', '4 day'])
        assert obj.dtype == 'timedelta64[ns]'

        # timedelta64 + timedelta64 => timedelta64
        exp = pd.TimedeltaIndex(['1 day', '10 day', '2 day', '3 day', '4 day'])
        self._assert_insert_conversion(obj, pd.Timedelta('10 day'),
                                       exp, 'timedelta64[ns]')

        # ToDo: must coerce to object
        msg = "cannot insert TimedeltaIndex with incompatible label"
        with pytest.raises(TypeError, match=msg):
            obj.insert(1, pd.Timestamp('2012-01-01'))

        # ToDo: must coerce to object
        msg = "cannot insert TimedeltaIndex with incompatible label"
        with pytest.raises(TypeError, match=msg):
            obj.insert(1, 1) 
Example #2
Source File: test_scalar_compat.py    From recruit with Apache License 2.0 7 votes vote down vote up
def test_tdi_round(self):
        td = pd.timedelta_range(start='16801 days', periods=5, freq='30Min')
        elt = td[1]

        expected_rng = TimedeltaIndex([Timedelta('16801 days 00:00:00'),
                                       Timedelta('16801 days 00:00:00'),
                                       Timedelta('16801 days 01:00:00'),
                                       Timedelta('16801 days 02:00:00'),
                                       Timedelta('16801 days 02:00:00')])
        expected_elt = expected_rng[1]

        tm.assert_index_equal(td.round(freq='H'), expected_rng)
        assert elt.round(freq='H') == expected_elt

        msg = pd._libs.tslibs.frequencies.INVALID_FREQ_ERR_MSG
        with pytest.raises(ValueError, match=msg):
            td.round(freq='foo')
        with pytest.raises(ValueError, match=msg):
            elt.round(freq='foo')

        msg = "<MonthEnd> is a non-fixed frequency"
        with pytest.raises(ValueError, match=msg):
            td.round(freq='M')
        with pytest.raises(ValueError, match=msg):
            elt.round(freq='M') 
Example #3
Source File: test_timedelta64.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_td64arr_add_offset_array(self, box):
        # GH#18849
        tdi = TimedeltaIndex(['1 days 00:00:00', '3 days 04:00:00'])
        other = np.array([pd.offsets.Hour(n=1), pd.offsets.Minute(n=-2)])

        expected = TimedeltaIndex([tdi[n] + other[n] for n in range(len(tdi))],
                                  freq='infer')

        tdi = tm.box_expected(tdi, box)
        expected = tm.box_expected(expected, box)

        # The DataFrame operation is transposed and so operates as separate
        #  scalar operations, which do not issue a PerformanceWarning
        warn = PerformanceWarning if box is not pd.DataFrame else None
        with tm.assert_produces_warning(warn):
            res = tdi + other
        tm.assert_equal(res, expected)

        with tm.assert_produces_warning(warn):
            res2 = other + tdi
        tm.assert_equal(res2, expected) 
Example #4
Source File: test_timedelta.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_sort_values(self):

        idx = TimedeltaIndex(['4d', '1d', '2d'])

        ordered = idx.sort_values()
        assert ordered.is_monotonic

        ordered = idx.sort_values(ascending=False)
        assert ordered[::-1].is_monotonic

        ordered, dexer = idx.sort_values(return_indexer=True)
        assert ordered.is_monotonic

        tm.assert_numpy_array_equal(dexer, np.array([1, 2, 0]),
                                    check_dtype=False)

        ordered, dexer = idx.sort_values(return_indexer=True, ascending=False)
        assert ordered[::-1].is_monotonic

        tm.assert_numpy_array_equal(dexer, np.array([0, 2, 1]),
                                    check_dtype=False) 
Example #5
Source File: test_timedelta64.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_td64arr_add_sub_td64_nat(self, box):
        # GH#23320 special handling for timedelta64("NaT")
        tdi = pd.TimedeltaIndex([NaT, Timedelta('1s')])
        other = np.timedelta64("NaT")
        expected = pd.TimedeltaIndex(["NaT"] * 2)

        obj = tm.box_expected(tdi, box)
        expected = tm.box_expected(expected, box)

        result = obj + other
        tm.assert_equal(result, expected)
        result = other + obj
        tm.assert_equal(result, expected)
        result = obj - other
        tm.assert_equal(result, expected)
        result = other - obj
        tm.assert_equal(result, expected) 
Example #6
Source File: test_timedelta.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_factorize(self):
        idx1 = TimedeltaIndex(['1 day', '1 day', '2 day', '2 day', '3 day',
                               '3 day'])

        exp_arr = np.array([0, 0, 1, 1, 2, 2], dtype=np.intp)
        exp_idx = TimedeltaIndex(['1 day', '2 day', '3 day'])

        arr, idx = idx1.factorize()
        tm.assert_numpy_array_equal(arr, exp_arr)
        tm.assert_index_equal(idx, exp_idx)

        arr, idx = idx1.factorize(sort=True)
        tm.assert_numpy_array_equal(arr, exp_arr)
        tm.assert_index_equal(idx, exp_idx)

        # freq must be preserved
        idx3 = timedelta_range('1 day', periods=4, freq='s')
        exp_arr = np.array([0, 1, 2, 3], dtype=np.intp)
        arr, idx = idx3.factorize()
        tm.assert_numpy_array_equal(arr, exp_arr)
        tm.assert_index_equal(idx, idx3) 
Example #7
Source File: test_timedelta.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_difference_sort(self, sort):

        index = pd.TimedeltaIndex(["5 days", "3 days", "2 days", "4 days",
                                   "1 days", "0 days"])

        other = timedelta_range("1 days", "4 days", freq="D")
        idx_diff = index.difference(other, sort)

        expected = TimedeltaIndex(["5 days", "0 days"], freq=None)

        if sort is None:
            expected = expected.sort_values()

        tm.assert_index_equal(idx_diff, expected)
        tm.assert_attr_equal('freq', idx_diff, expected)

        other = timedelta_range("2 days", "5 days", freq="D")
        idx_diff = index.difference(other, sort)
        expected = TimedeltaIndex(["1 days", "0 days"], freq=None)

        if sort is None:
            expected = expected.sort_values()

        tm.assert_index_equal(idx_diff, expected)
        tm.assert_attr_equal('freq', idx_diff, expected) 
Example #8
Source File: test_ops.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_nat(self):
        assert pd.TimedeltaIndex._na_value is pd.NaT
        assert pd.TimedeltaIndex([])._na_value is pd.NaT

        idx = pd.TimedeltaIndex(['1 days', '2 days'])
        assert idx._can_hold_na

        tm.assert_numpy_array_equal(idx._isnan, np.array([False, False]))
        assert idx.hasnans is False
        tm.assert_numpy_array_equal(idx._nan_idxs,
                                    np.array([], dtype=np.intp))

        idx = pd.TimedeltaIndex(['1 days', 'NaT'])
        assert idx._can_hold_na

        tm.assert_numpy_array_equal(idx._isnan, np.array([False, True]))
        assert idx.hasnans is True
        tm.assert_numpy_array_equal(idx._nan_idxs,
                                    np.array([1], dtype=np.intp)) 
Example #9
Source File: test_timedelta64.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_td64arr_sub_offset_index(self, names, box):
        # GH#18824, GH#19744
        if box is pd.DataFrame and names[1] == 'bar':
            pytest.skip("Name propagation for DataFrame does not behave like "
                        "it does for Index/Series")

        tdi = TimedeltaIndex(['1 days 00:00:00', '3 days 04:00:00'],
                             name=names[0])
        other = pd.Index([pd.offsets.Hour(n=1), pd.offsets.Minute(n=-2)],
                         name=names[1])

        expected = TimedeltaIndex([tdi[n] - other[n] for n in range(len(tdi))],
                                  freq='infer', name=names[2])

        tdi = tm.box_expected(tdi, box)
        expected = tm.box_expected(expected, box)

        # The DataFrame operation is transposed and so operates as separate
        #  scalar operations, which do not issue a PerformanceWarning
        warn = PerformanceWarning if box is not pd.DataFrame else None
        with tm.assert_produces_warning(warn):
            res = tdi - other
        tm.assert_equal(res, expected) 
Example #10
Source File: test_timedelta64.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_td64arr_sub_offset_array(self, box_with_array):
        # GH#18824
        tdi = TimedeltaIndex(['1 days 00:00:00', '3 days 04:00:00'])
        other = np.array([pd.offsets.Hour(n=1), pd.offsets.Minute(n=-2)])

        expected = TimedeltaIndex([tdi[n] - other[n] for n in range(len(tdi))],
                                  freq='infer')

        tdi = tm.box_expected(tdi, box_with_array)
        expected = tm.box_expected(expected, box_with_array)

        # The DataFrame operation is transposed and so operates as separate
        #  scalar operations, which do not issue a PerformanceWarning
        warn = None if box_with_array is pd.DataFrame else PerformanceWarning
        with tm.assert_produces_warning(warn):
            res = tdi - other
        tm.assert_equal(res, expected) 
Example #11
Source File: test_timedelta.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_difference_freq(self, sort):
        # GH14323: Difference of TimedeltaIndex should not preserve frequency

        index = timedelta_range("0 days", "5 days", freq="D")

        other = timedelta_range("1 days", "4 days", freq="D")
        expected = TimedeltaIndex(["0 days", "5 days"], freq=None)
        idx_diff = index.difference(other, sort)
        tm.assert_index_equal(idx_diff, expected)
        tm.assert_attr_equal('freq', idx_diff, expected)

        other = timedelta_range("2 days", "5 days", freq="D")
        idx_diff = index.difference(other, sort)
        expected = TimedeltaIndex(["0 days", "1 days"], freq=None)
        tm.assert_index_equal(idx_diff, expected)
        tm.assert_attr_equal('freq', idx_diff, expected) 
Example #12
Source File: test_timedelta64.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_td64arr_add_timestamp(self, box_with_array, tz_naive_fixture):
        # GH#23215

        # TODO: parametrize over scalar datetime types?
        tz = tz_naive_fixture
        other = Timestamp('2011-01-01', tz=tz)

        idx = TimedeltaIndex(['1 day', '2 day'])
        expected = DatetimeIndex(['2011-01-02', '2011-01-03'], tz=tz)

        # FIXME: fails with transpose=True because of tz-aware DataFrame
        #  transpose bug
        idx = tm.box_expected(idx, box_with_array, transpose=False)
        expected = tm.box_expected(expected, box_with_array, transpose=False)

        result = idx + other
        tm.assert_equal(result, expected)

        result = other + idx
        tm.assert_equal(result, expected) 
Example #13
Source File: test_indexing.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_take(self):
        # GH 10295
        idx1 = timedelta_range('1 day', '31 day', freq='D', name='idx')

        for idx in [idx1]:
            result = idx.take([0])
            assert result == Timedelta('1 day')

            result = idx.take([-1])
            assert result == Timedelta('31 day')

            result = idx.take([0, 1, 2])
            expected = timedelta_range('1 day', '3 day', freq='D',
                                       name='idx')
            tm.assert_index_equal(result, expected)
            assert result.freq == expected.freq

            result = idx.take([0, 2, 4])
            expected = timedelta_range('1 day', '5 day', freq='2D',
                                       name='idx')
            tm.assert_index_equal(result, expected)
            assert result.freq == expected.freq

            result = idx.take([7, 4, 1])
            expected = timedelta_range('8 day', '2 day', freq='-3D',
                                       name='idx')
            tm.assert_index_equal(result, expected)
            assert result.freq == expected.freq

            result = idx.take([3, 2, 5])
            expected = TimedeltaIndex(['4 day', '3 day', '6 day'], name='idx')
            tm.assert_index_equal(result, expected)
            assert result.freq is None

            result = idx.take([-3, 2, 5])
            expected = TimedeltaIndex(['29 day', '3 day', '6 day'], name='idx')
            tm.assert_index_equal(result, expected)
            assert result.freq is None 
Example #14
Source File: test_indexing.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_take2(self):
        tds = ['1day 02:00:00', '1 day 04:00:00', '1 day 10:00:00']
        idx = timedelta_range(start='1d', end='2d', freq='H', name='idx')
        expected = TimedeltaIndex(tds, freq=None, name='idx')

        taken1 = idx.take([2, 4, 10])
        taken2 = idx[[2, 4, 10]]

        for taken in [taken1, taken2]:
            tm.assert_index_equal(taken, expected)
            assert isinstance(taken, TimedeltaIndex)
            assert taken.freq is None
            assert taken.name == expected.name 
Example #15
Source File: test_ops.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_equals(self):
        # GH 13107
        idx = pd.TimedeltaIndex(['1 days', '2 days', 'NaT'])
        assert idx.equals(idx)
        assert idx.equals(idx.copy())
        assert idx.equals(idx.astype(object))
        assert idx.astype(object).equals(idx)
        assert idx.astype(object).equals(idx.astype(object))
        assert not idx.equals(list(idx))
        assert not idx.equals(pd.Series(idx))

        idx2 = pd.TimedeltaIndex(['2 days', '1 days', 'NaT'])
        assert not idx.equals(idx2)
        assert not idx.equals(idx2.copy())
        assert not idx.equals(idx2.astype(object))
        assert not idx.astype(object).equals(idx2)
        assert not idx.astype(object).equals(idx2.astype(object))
        assert not idx.equals(list(idx2))
        assert not idx.equals(pd.Series(idx2)) 
Example #16
Source File: test_ops.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_freq_setter_errors(self):
        # GH 20678
        idx = TimedeltaIndex(['0 days', '2 days', '4 days'])

        # setting with an incompatible freq
        msg = ('Inferred frequency 2D from passed values does not conform to '
               'passed frequency 5D')
        with pytest.raises(ValueError, match=msg):
            idx.freq = '5D'

        # setting with a non-fixed frequency
        msg = r'<2 \* BusinessDays> is a non-fixed frequency'
        with pytest.raises(ValueError, match=msg):
            idx.freq = '2B'

        # setting with non-freq string
        with pytest.raises(ValueError, match='Invalid frequency'):
            idx.freq = 'foo' 
Example #17
Source File: test_timedelta64.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_dti_tdi_numeric_ops(self):
        # These are normally union/diff set-like ops
        tdi = TimedeltaIndex(['1 days', pd.NaT, '2 days'], name='foo')
        dti = pd.date_range('20130101', periods=3, name='bar')

        # TODO(wesm): unused?
        # td = Timedelta('1 days')
        # dt = Timestamp('20130101')

        result = tdi - tdi
        expected = TimedeltaIndex(['0 days', pd.NaT, '0 days'], name='foo')
        tm.assert_index_equal(result, expected)

        result = tdi + tdi
        expected = TimedeltaIndex(['2 days', pd.NaT, '4 days'], name='foo')
        tm.assert_index_equal(result, expected)

        result = dti - tdi  # name will be reset
        expected = DatetimeIndex(['20121231', pd.NaT, '20130101'])
        tm.assert_index_equal(result, expected) 
Example #18
Source File: test_arithmetic.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_tdi_addsub_integer_array_no_freq(self, box):
        # GH#19959
        tdi = TimedeltaIndex(['1 Day', 'NaT', '3 Hours'])
        other = box([14, -1, 16])
        with pytest.raises(NullFrequencyError):
            tdi + other
        with pytest.raises(NullFrequencyError):
            other + tdi
        with pytest.raises(NullFrequencyError):
            tdi - other
        with pytest.raises(NullFrequencyError):
            other - tdi

    # -------------------------------------------------------------
    # Binary operations TimedeltaIndex and timedelta-like
    # Note: add and sub are tested in tests.test_arithmetic, in-place
    #  tests are kept here because their behavior is Index-specific 
Example #19
Source File: test_timedelta64.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_tdi_cmp_str_invalid(self, box_with_array):
        # GH#13624
        xbox = box_with_array if box_with_array is not pd.Index else np.ndarray
        tdi = TimedeltaIndex(['1 day', '2 days'])
        tdarr = tm.box_expected(tdi, box_with_array)

        for left, right in [(tdarr, 'a'), ('a', tdarr)]:
            with pytest.raises(TypeError):
                left > right
            with pytest.raises(TypeError):
                left >= right
            with pytest.raises(TypeError):
                left < right
            with pytest.raises(TypeError):
                left <= right

            result = left == right
            expected = np.array([False, False], dtype=bool)
            expected = tm.box_expected(expected, xbox)
            tm.assert_equal(result, expected)

            result = left != right
            expected = np.array([True, True], dtype=bool)
            expected = tm.box_expected(expected, xbox)
            tm.assert_equal(result, expected) 
Example #20
Source File: test_construction.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_float64_ns_rounded(self):
        # GH#23539 without specifying a unit, floats are regarded as nanos,
        #  and fractional portions are truncated
        tdi = TimedeltaIndex([2.3, 9.7])
        expected = TimedeltaIndex([2, 9])
        tm.assert_index_equal(tdi, expected)

        # integral floats are non-lossy
        tdi = TimedeltaIndex([2.0, 9.0])
        expected = TimedeltaIndex([2, 9])
        tm.assert_index_equal(tdi, expected)

        # NaNs get converted to NaT
        tdi = TimedeltaIndex([2.0, np.nan])
        expected = TimedeltaIndex([pd.Timedelta(nanoseconds=2), pd.NaT])
        tm.assert_index_equal(tdi, expected) 
Example #21
Source File: test_formats.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_representation_to_series(self):
        idx1 = TimedeltaIndex([], freq='D')
        idx2 = TimedeltaIndex(['1 days'], freq='D')
        idx3 = TimedeltaIndex(['1 days', '2 days'], freq='D')
        idx4 = TimedeltaIndex(['1 days', '2 days', '3 days'], freq='D')
        idx5 = TimedeltaIndex(['1 days 00:00:01', '2 days', '3 days'])

        exp1 = """Series([], dtype: timedelta64[ns])"""

        exp2 = ("0   1 days\n"
                "dtype: timedelta64[ns]")

        exp3 = ("0   1 days\n"
                "1   2 days\n"
                "dtype: timedelta64[ns]")

        exp4 = ("0   1 days\n"
                "1   2 days\n"
                "2   3 days\n"
                "dtype: timedelta64[ns]")

        exp5 = ("0   1 days 00:00:01\n"
                "1   2 days 00:00:00\n"
                "2   3 days 00:00:00\n"
                "dtype: timedelta64[ns]")

        with pd.option_context('display.width', 300):
            for idx, expected in zip([idx1, idx2, idx3, idx4, idx5],
                                     [exp1, exp2, exp3, exp4, exp5]):
                result = repr(pd.Series(idx))
                assert result == expected 
Example #22
Source File: test_formats.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_summary(self):
        # GH#9116
        idx1 = TimedeltaIndex([], freq='D')
        idx2 = TimedeltaIndex(['1 days'], freq='D')
        idx3 = TimedeltaIndex(['1 days', '2 days'], freq='D')
        idx4 = TimedeltaIndex(['1 days', '2 days', '3 days'], freq='D')
        idx5 = TimedeltaIndex(['1 days 00:00:01', '2 days', '3 days'])

        exp1 = ("TimedeltaIndex: 0 entries\n"
                "Freq: D")

        exp2 = ("TimedeltaIndex: 1 entries, 1 days to 1 days\n"
                "Freq: D")

        exp3 = ("TimedeltaIndex: 2 entries, 1 days to 2 days\n"
                "Freq: D")

        exp4 = ("TimedeltaIndex: 3 entries, 1 days to 3 days\n"
                "Freq: D")

        exp5 = ("TimedeltaIndex: 3 entries, 1 days 00:00:01 to 3 days "
                "00:00:00")

        for idx, expected in zip([idx1, idx2, idx3, idx4, idx5],
                                 [exp1, exp2, exp3, exp4, exp5]):
            result = idx._summary()
            assert result == expected 
Example #23
Source File: test_formats.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_representation(self, method):
        idx1 = TimedeltaIndex([], freq='D')
        idx2 = TimedeltaIndex(['1 days'], freq='D')
        idx3 = TimedeltaIndex(['1 days', '2 days'], freq='D')
        idx4 = TimedeltaIndex(['1 days', '2 days', '3 days'], freq='D')
        idx5 = TimedeltaIndex(['1 days 00:00:01', '2 days', '3 days'])

        exp1 = """TimedeltaIndex([], dtype='timedelta64[ns]', freq='D')"""

        exp2 = ("TimedeltaIndex(['1 days'], dtype='timedelta64[ns]', "
                "freq='D')")

        exp3 = ("TimedeltaIndex(['1 days', '2 days'], "
                "dtype='timedelta64[ns]', freq='D')")

        exp4 = ("TimedeltaIndex(['1 days', '2 days', '3 days'], "
                "dtype='timedelta64[ns]', freq='D')")

        exp5 = ("TimedeltaIndex(['1 days 00:00:01', '2 days 00:00:00', "
                "'3 days 00:00:00'], dtype='timedelta64[ns]', freq=None)")

        with pd.option_context('display.width', 300):
            for idx, expected in zip([idx1, idx2, idx3, idx4, idx5],
                                     [exp1, exp2, exp3, exp4, exp5]):
                result = getattr(idx, method)()
                assert result == expected 
Example #24
Source File: test_arithmetic.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_tdi_sub_integer_array(self, box):
        # GH#19959
        rng = timedelta_range('9H', freq='H', periods=3)
        other = box([4, 3, 2])
        expected = TimedeltaIndex(['5H', '7H', '9H'])
        with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
            # GH#22535
            result = rng - other
            tm.assert_index_equal(result, expected)

        with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
            # GH#22535
            result = other - rng
            tm.assert_index_equal(result, -expected) 
Example #25
Source File: test_ops.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_infer_freq(self, freq):
        # GH#11018
        idx = pd.timedelta_range('1', freq=freq, periods=10)
        result = pd.TimedeltaIndex(idx.asi8, freq='infer')
        tm.assert_index_equal(idx, result)
        assert result.freq == freq 
Example #26
Source File: test_ops.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_nonunique_contains(self):
        # GH 9512
        for idx in map(TimedeltaIndex, ([0, 1, 0], [0, 0, -1], [0, -1, -1],
                                        ['00:01:00', '00:01:00', '00:02:00'],
                                        ['00:01:00', '00:01:00', '00:00:01'])):
            assert idx[0] in idx 
Example #27
Source File: test_concat.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_concatlike_common_coerce_to_pandas_object(self):
        # GH 13626
        # result must be Timestamp/Timedelta, not datetime.datetime/timedelta
        dti = pd.DatetimeIndex(['2011-01-01', '2011-01-02'])
        tdi = pd.TimedeltaIndex(['1 days', '2 days'])

        exp = pd.Index([pd.Timestamp('2011-01-01'),
                        pd.Timestamp('2011-01-02'),
                        pd.Timedelta('1 days'),
                        pd.Timedelta('2 days')])

        res = dti.append(tdi)
        tm.assert_index_equal(res, exp)
        assert isinstance(res[0], pd.Timestamp)
        assert isinstance(res[-1], pd.Timedelta)

        dts = pd.Series(dti)
        tds = pd.Series(tdi)
        res = dts.append(tds)
        tm.assert_series_equal(res, pd.Series(exp, index=[0, 1, 0, 1]))
        assert isinstance(res.iloc[0], pd.Timestamp)
        assert isinstance(res.iloc[-1], pd.Timedelta)

        res = pd.concat([dts, tds])
        tm.assert_series_equal(res, pd.Series(exp, index=[0, 1, 0, 1]))
        assert isinstance(res.iloc[0], pd.Timestamp)
        assert isinstance(res.iloc[-1], pd.Timedelta) 
Example #28
Source File: test_ops.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_repeat(self):
        index = pd.timedelta_range('1 days', periods=2, freq='D')
        exp = pd.TimedeltaIndex(['1 days', '1 days', '2 days', '2 days'])
        for res in [index.repeat(2), np.repeat(index, 2)]:
            tm.assert_index_equal(res, exp)
            assert res.freq is None

        index = TimedeltaIndex(['1 days', 'NaT', '3 days'])
        exp = TimedeltaIndex(['1 days', '1 days', '1 days',
                              'NaT', 'NaT', 'NaT',
                              '3 days', '3 days', '3 days'])
        for res in [index.repeat(3), np.repeat(index, 3)]:
            tm.assert_index_equal(res, exp)
            assert res.freq is None 
Example #29
Source File: test_concat.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_concatlike_common_period_mixed_dt_to_object(self):
        # GH 13221
        # different datetimelike
        pi1 = pd.PeriodIndex(['2011-01', '2011-02'], freq='M')
        tdi = pd.TimedeltaIndex(['1 days', '2 days'])
        exp = pd.Index([pd.Period('2011-01', freq='M'),
                        pd.Period('2011-02', freq='M'),
                        pd.Timedelta('1 days'),
                        pd.Timedelta('2 days')], dtype=object)

        res = pi1.append(tdi)
        tm.assert_index_equal(res, exp)

        ps1 = pd.Series(pi1)
        tds = pd.Series(tdi)
        res = ps1.append(tds)
        tm.assert_series_equal(res, pd.Series(exp, index=[0, 1, 0, 1]))

        res = pd.concat([ps1, tds])
        tm.assert_series_equal(res, pd.Series(exp, index=[0, 1, 0, 1]))

        # inverse
        exp = pd.Index([pd.Timedelta('1 days'),
                        pd.Timedelta('2 days'),
                        pd.Period('2011-01', freq='M'),
                        pd.Period('2011-02', freq='M')], dtype=object)

        res = tdi.append(pi1)
        tm.assert_index_equal(res, exp)

        ps1 = pd.Series(pi1)
        tds = pd.Series(tdi)
        res = tds.append(ps1)
        tm.assert_series_equal(res, pd.Series(exp, index=[0, 1, 0, 1]))

        res = pd.concat([tds, ps1])
        tm.assert_series_equal(res, pd.Series(exp, index=[0, 1, 0, 1])) 
Example #30
Source File: test_base.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_constructor_dtypes_to_timedelta(self, cast_index, vals):
        if cast_index:
            index = Index(vals, dtype=object)
            assert isinstance(index, Index)
            assert index.dtype == object
        else:
            index = Index(vals)
            assert isinstance(index, TimedeltaIndex)