Python pandas.Timedelta() Examples
The following are 30
code examples of pandas.Timedelta().
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 |
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 |
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_to_csv.py From recruit with Apache License 2.0 | 6 votes |
def test_to_csv_from_csv4(self): with ensure_clean('__tmp_to_csv_from_csv4__') as path: # GH 10833 (TimedeltaIndex formatting) dt = pd.Timedelta(seconds=1) df = pd.DataFrame({'dt_data': [i * dt for i in range(3)]}, index=pd.Index([i * dt for i in range(3)], name='dt_index')) df.to_csv(path) result = pd.read_csv(path, index_col='dt_index') result.index = pd.to_timedelta(result.index) # TODO: remove renaming when GH 10875 is solved result.index = result.index.rename('dt_index') result['dt_data'] = pd.to_timedelta(result['dt_data']) assert_frame_equal(df, result, check_index_type=True)
Example #4
Source File: test_interval.py From recruit with Apache License 2.0 | 6 votes |
def test_get_loc_datetimelike_overlapping(self, arrays): # GH 20636 # overlapping = IntervalTree method with i8 conversion index = IntervalIndex.from_arrays(*arrays) value = index[0].mid + Timedelta('12 hours') result = np.sort(index.get_loc(value)) expected = np.array([0, 1], dtype='intp') assert tm.assert_numpy_array_equal(result, expected) interval = Interval(index[0].left, index[1].right) result = np.sort(index.get_loc(interval)) expected = np.array([0, 1, 2], dtype='intp') assert tm.assert_numpy_array_equal(result, expected) # To be removed, replaced by test_interval_new.py (see #16316, #16386)
Example #5
Source File: test_indexing.py From recruit with Apache License 2.0 | 6 votes |
def test_get_indexer(self): idx = pd.to_timedelta(['0 days', '1 days', '2 days']) tm.assert_numpy_array_equal(idx.get_indexer(idx), np.array([0, 1, 2], dtype=np.intp)) target = pd.to_timedelta(['-1 hour', '12 hours', '1 day 1 hour']) tm.assert_numpy_array_equal(idx.get_indexer(target, 'pad'), np.array([-1, 0, 1], dtype=np.intp)) tm.assert_numpy_array_equal(idx.get_indexer(target, 'backfill'), np.array([0, 1, 2], dtype=np.intp)) tm.assert_numpy_array_equal(idx.get_indexer(target, 'nearest'), np.array([0, 1, 1], dtype=np.intp)) res = idx.get_indexer(target, 'nearest', tolerance=Timedelta('1 hour')) tm.assert_numpy_array_equal(res, np.array([0, -1, 1], dtype=np.intp))
Example #6
Source File: test_analytics.py From recruit with Apache License 2.0 | 6 votes |
def test_isin_empty_datetimelike(self): # GH 15473 df1_ts = DataFrame({'date': pd.to_datetime(['2014-01-01', '2014-01-02'])}) df1_td = DataFrame({'date': [pd.Timedelta(1, 's'), pd.Timedelta(2, 's')]}) df2 = DataFrame({'date': []}) df3 = DataFrame() expected = DataFrame({'date': [False, False]}) result = df1_ts.isin(df2) tm.assert_frame_equal(result, expected) result = df1_ts.isin(df3) tm.assert_frame_equal(result, expected) result = df1_td.isin(df2) tm.assert_frame_equal(result, expected) result = df1_td.isin(df3) tm.assert_frame_equal(result, expected) # Rounding
Example #7
Source File: test_indexing.py From recruit with Apache License 2.0 | 6 votes |
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 #8
Source File: test_astype.py From recruit with Apache License 2.0 | 6 votes |
def test_astype(self): # GH 13149, GH 13209 idx = TimedeltaIndex([1e14, 'NaT', NaT, np.NaN]) result = idx.astype(object) expected = Index([Timedelta('1 days 03:46:40')] + [NaT] * 3, dtype=object) tm.assert_index_equal(result, expected) result = idx.astype(int) expected = Int64Index([100000000000000] + [-9223372036854775808] * 3, dtype=np.int64) tm.assert_index_equal(result, expected) result = idx.astype(str) expected = Index(str(x) for x in idx) tm.assert_index_equal(result, expected) rng = timedelta_range('1 days', periods=10) result = rng.astype('i8') tm.assert_index_equal(result, Index(rng.asi8)) tm.assert_numpy_array_equal(rng.asi8, result.values)
Example #9
Source File: test_ticks.py From recruit with Apache License 2.0 | 6 votes |
def test_compare_ticks_to_strs(cls): # GH#23524 off = cls(19) # These tests should work with any strings, but we particularly are # interested in "infer" as that comparison is convenient to make in # Datetime/Timedelta Array/Index constructors assert not off == "infer" assert not "foo" == off for left, right in [("infer", off), (off, "infer")]: with pytest.raises(TypeError): left < right with pytest.raises(TypeError): left <= right with pytest.raises(TypeError): left > right with pytest.raises(TypeError): left >= right
Example #10
Source File: test_timedelta64.py From recruit with Apache License 2.0 | 6 votes |
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 #11
Source File: test_timedelta64.py From recruit with Apache License 2.0 | 6 votes |
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 #12
Source File: test_datetimelike.py From recruit with Apache License 2.0 | 6 votes |
def test_take_fill_valid(self, timedelta_index): tdi = timedelta_index arr = TimedeltaArray(tdi) td1 = pd.Timedelta(days=1) result = arr.take([-1, 1], allow_fill=True, fill_value=td1) assert result[0] == td1 now = pd.Timestamp.now() with pytest.raises(ValueError): # fill_value Timestamp invalid arr.take([0, 1], allow_fill=True, fill_value=now) with pytest.raises(ValueError): # fill_value Period invalid arr.take([0, 1], allow_fill=True, fill_value=now.to_period('D'))
Example #13
Source File: test_ticks.py From recruit with Apache License 2.0 | 6 votes |
def test_tick_division(cls): off = cls(10) assert off / cls(5) == 2 assert off / 2 == cls(5) assert off / 2.0 == cls(5) assert off / off.delta == 1 assert off / off.delta.to_timedelta64() == 1 assert off / Nano(1) == off.delta / Nano(1).delta if cls is not Nano: # A case where we end up with a smaller class result = off / 1000 assert isinstance(result, offsets.Tick) assert not isinstance(result, cls) assert result.delta == off.delta / 1000 if cls._inc < Timedelta(seconds=1): # Case where we end up with a bigger class result = off / .001 assert isinstance(result, offsets.Tick) assert not isinstance(result, cls) assert result.delta == off.delta / .001
Example #14
Source File: test_timedeltas.py From recruit with Apache License 2.0 | 6 votes |
def test_min_max(self): arr = TimedeltaArray._from_sequence([ '3H', '3H', 'NaT', '2H', '5H', '4H', ]) result = arr.min() expected = pd.Timedelta('2H') assert result == expected result = arr.max() expected = pd.Timedelta('5H') assert result == expected result = arr.min(skipna=False) assert result is pd.NaT result = arr.max(skipna=False) assert result is pd.NaT
Example #15
Source File: test_timedelta64.py From recruit with Apache License 2.0 | 6 votes |
def test_timedelta64_conversions(self, m, unit): startdate = Series(pd.date_range('2013-01-01', '2013-01-03')) enddate = Series(pd.date_range('2013-03-01', '2013-03-03')) ser = enddate - startdate ser[2] = np.nan # op expected = Series([x / np.timedelta64(m, unit) for x in ser]) result = ser / np.timedelta64(m, unit) tm.assert_series_equal(result, expected) # reverse op expected = Series([Timedelta(np.timedelta64(m, unit)) / x for x in ser]) result = np.timedelta64(m, unit) / ser tm.assert_series_equal(result, expected) # ------------------------------------------------------------------ # Multiplication # organized with scalar others first, then array-like
Example #16
Source File: test_partial_slicing.py From recruit with Apache License 2.0 | 6 votes |
def test_slice_with_negative_step(self): ts = Series(np.arange(20), timedelta_range('0', periods=20, freq='H')) SLC = pd.IndexSlice def assert_slices_equivalent(l_slc, i_slc): assert_series_equal(ts[l_slc], ts.iloc[i_slc]) assert_series_equal(ts.loc[l_slc], ts.iloc[i_slc]) assert_series_equal(ts.loc[l_slc], ts.iloc[i_slc]) assert_slices_equivalent(SLC[Timedelta(hours=7)::-1], SLC[7::-1]) assert_slices_equivalent(SLC['7 hours'::-1], SLC[7::-1]) assert_slices_equivalent(SLC[:Timedelta(hours=7):-1], SLC[:6:-1]) assert_slices_equivalent(SLC[:'7 hours':-1], SLC[:6:-1]) assert_slices_equivalent(SLC['15 hours':'7 hours':-1], SLC[15:6:-1]) assert_slices_equivalent(SLC[Timedelta(hours=15):Timedelta(hours=7):- 1], SLC[15:6:-1]) assert_slices_equivalent(SLC['15 hours':Timedelta(hours=7):-1], SLC[15:6:-1]) assert_slices_equivalent(SLC[Timedelta(hours=15):'7 hours':-1], SLC[15:6:-1]) assert_slices_equivalent(SLC['7 hours':'15 hours':-1], SLC[:0])
Example #17
Source File: test_indexing.py From recruit with Apache License 2.0 | 6 votes |
def test_timedelta_assignment(): # GH 8209 s = Series([]) s.loc['B'] = timedelta(1) tm.assert_series_equal(s, Series(Timedelta('1 days'), index=['B'])) s = s.reindex(s.index.insert(0, 'A')) tm.assert_series_equal(s, Series( [np.nan, Timedelta('1 days')], index=['A', 'B'])) result = s.fillna(timedelta(1)) expected = Series(Timedelta('1 days'), index=['A', 'B']) tm.assert_series_equal(result, expected) s.loc['A'] = timedelta(1) tm.assert_series_equal(s, expected) # GH 14155 s = Series(10 * [np.timedelta64(10, 'm')]) s.loc[[1, 2, 3]] = np.timedelta64(20, 'm') expected = pd.Series(10 * [np.timedelta64(10, 'm')]) expected.loc[[1, 2, 3]] = pd.Timedelta(np.timedelta64(20, 'm')) tm.assert_series_equal(s, expected)
Example #18
Source File: test_base.py From recruit with Apache License 2.0 | 6 votes |
def test_constructor_from_index_dtlike(self, cast_as_obj, index): if cast_as_obj: result = pd.Index(index.astype(object)) else: result = pd.Index(index) tm.assert_index_equal(result, index) if isinstance(index, pd.DatetimeIndex): assert result.tz == index.tz if cast_as_obj: # GH#23524 check that Index(dti, dtype=object) does not # incorrectly raise ValueError, and that nanoseconds are not # dropped index += pd.Timedelta(nanoseconds=50) result = pd.Index(index, dtype=object) assert result.dtype == np.object_ assert list(result) == list(index)
Example #19
Source File: test_merge_asof.py From recruit with Apache License 2.0 | 6 votes |
def test_tolerance_tz(self): # GH 14844 left = pd.DataFrame( {'date': pd.date_range(start=pd.to_datetime('2016-01-02'), freq='D', periods=5, tz=pytz.timezone('UTC')), 'value1': np.arange(5)}) right = pd.DataFrame( {'date': pd.date_range(start=pd.to_datetime('2016-01-01'), freq='D', periods=5, tz=pytz.timezone('UTC')), 'value2': list("ABCDE")}) result = pd.merge_asof(left, right, on='date', tolerance=pd.Timedelta('1 day')) expected = pd.DataFrame( {'date': pd.date_range(start=pd.to_datetime('2016-01-02'), freq='D', periods=5, tz=pytz.timezone('UTC')), 'value1': np.arange(5), 'value2': list("BCDEE")}) assert_frame_equal(result, expected)
Example #20
Source File: test_apply.py From recruit with Apache License 2.0 | 5 votes |
def test_map_box(self): vals = [pd.Timestamp('2011-01-01'), pd.Timestamp('2011-01-02')] s = pd.Series(vals) assert s.dtype == 'datetime64[ns]' # boxed value must be Timestamp instance res = s.map(lambda x: '{0}_{1}_{2}'.format(x.__class__.__name__, x.day, x.tz)) exp = pd.Series(['Timestamp_1_None', 'Timestamp_2_None']) tm.assert_series_equal(res, exp) vals = [pd.Timestamp('2011-01-01', tz='US/Eastern'), pd.Timestamp('2011-01-02', tz='US/Eastern')] s = pd.Series(vals) assert s.dtype == 'datetime64[ns, US/Eastern]' res = s.map(lambda x: '{0}_{1}_{2}'.format(x.__class__.__name__, x.day, x.tz)) exp = pd.Series(['Timestamp_1_US/Eastern', 'Timestamp_2_US/Eastern']) tm.assert_series_equal(res, exp) # timedelta vals = [pd.Timedelta('1 days'), pd.Timedelta('2 days')] s = pd.Series(vals) assert s.dtype == 'timedelta64[ns]' res = s.map(lambda x: '{0}_{1}'.format(x.__class__.__name__, x.days)) exp = pd.Series(['Timedelta_1', 'Timedelta_2']) tm.assert_series_equal(res, exp) # period vals = [pd.Period('2011-01-01', freq='M'), pd.Period('2011-01-02', freq='M')] s = pd.Series(vals) assert s.dtype == 'Period[M]' res = s.map(lambda x: '{0}_{1}'.format(x.__class__.__name__, x.freqstr)) exp = pd.Series(['Period_M', 'Period_M']) tm.assert_series_equal(res, exp)
Example #21
Source File: test_quantile.py From recruit with Apache License 2.0 | 5 votes |
def test_quantile(self): q = self.ts.quantile(0.1) assert q == np.percentile(self.ts.dropna(), 10) q = self.ts.quantile(0.9) assert q == np.percentile(self.ts.dropna(), 90) # object dtype q = Series(self.ts, dtype=object).quantile(0.9) assert q == np.percentile(self.ts.dropna(), 90) # datetime64[ns] dtype dts = self.ts.index.to_series() q = dts.quantile(.2) assert q == Timestamp('2000-01-10 19:12:00') # timedelta64[ns] dtype tds = dts.diff() q = tds.quantile(.25) assert q == pd.to_timedelta('24:00:00') # GH7661 result = Series([np.timedelta64('NaT')]).sum() assert result == pd.Timedelta(0) msg = 'percentiles should all be in the interval \\[0, 1\\]' for invalid in [-1, 2, [0.5, -1], [0.5, 2]]: with pytest.raises(ValueError, match=msg): self.ts.quantile(invalid)
Example #22
Source File: test_datetime64.py From recruit with Apache License 2.0 | 5 votes |
def test_dti_cmp_object_dtype(self): # GH#22074 dti = date_range('2000-01-01', periods=10, tz='Asia/Tokyo') other = dti.astype('O') result = dti == other expected = np.array([True] * 10) tm.assert_numpy_array_equal(result, expected) other = dti.tz_localize(None) with pytest.raises(TypeError): # tzawareness failure dti != other other = np.array(list(dti[:5]) + [Timedelta(days=1)] * 5) result = dti == other expected = np.array([True] * 5 + [False] * 5) tm.assert_numpy_array_equal(result, expected) with pytest.raises(TypeError): dti >= other # ------------------------------------------------------------------ # Arithmetic
Example #23
Source File: test_coercion.py From recruit with Apache License 2.0 | 5 votes |
def test_setitem_series_timedelta64(self, val, exp_dtype): obj = pd.Series([pd.Timedelta('1 day'), pd.Timedelta('2 day'), pd.Timedelta('3 day'), pd.Timedelta('4 day')]) assert obj.dtype == 'timedelta64[ns]' exp = pd.Series([pd.Timedelta('1 day'), val, pd.Timedelta('3 day'), pd.Timedelta('4 day')]) self._assert_setitem_series_conversion(obj, val, exp, exp_dtype)
Example #24
Source File: test_scalar.py From recruit with Apache License 2.0 | 5 votes |
def test_at_iat_coercion(self): # as timestamp is not a tuple! dates = date_range('1/1/2000', periods=8) df = DataFrame(np.random.randn(8, 4), index=dates, columns=['A', 'B', 'C', 'D']) s = df['A'] result = s.at[dates[5]] xp = s.values[5] assert result == xp # GH 7729 # make sure we are boxing the returns s = Series(['2014-01-01', '2014-02-02'], dtype='datetime64[ns]') expected = Timestamp('2014-02-02') for r in [lambda: s.iat[1], lambda: s.iloc[1]]: result = r() assert result == expected s = Series(['1 days', '2 days'], dtype='timedelta64[ns]') expected = Timedelta('2 days') for r in [lambda: s.iat[1], lambda: s.iloc[1]]: result = r() assert result == expected
Example #25
Source File: test_to_csv.py From recruit with Apache License 2.0 | 5 votes |
def test_to_csv_with_dst_transitions(self): with ensure_clean('csv_date_format_with_dst') as path: # make sure we are not failing on transitions times = pd.date_range("2013-10-26 23:00", "2013-10-27 01:00", tz="Europe/London", freq="H", ambiguous='infer') for i in [times, times + pd.Timedelta('10s')]: time_range = np.array(range(len(i)), dtype='int64') df = DataFrame({'A': time_range}, index=i) df.to_csv(path, index=True) # we have to reconvert the index as we # don't parse the tz's result = read_csv(path, index_col=0) result.index = to_datetime(result.index, utc=True).tz_convert( 'Europe/London') assert_frame_equal(result, df) # GH11619 idx = pd.date_range('2015-01-01', '2015-12-31', freq='H', tz='Europe/Paris') df = DataFrame({'values': 1, 'idx': idx}, index=idx) with ensure_clean('csv_date_format_with_dst') as path: df.to_csv(path, index=True) result = read_csv(path, index_col=0) result.index = to_datetime(result.index, utc=True).tz_convert( 'Europe/Paris') result['idx'] = to_datetime(result['idx'], utc=True).astype( 'datetime64[ns, Europe/Paris]') assert_frame_equal(result, df) # assert working df.astype(str) with ensure_clean('csv_date_format_with_dst') as path: df.to_pickle(path) result = pd.read_pickle(path) assert_frame_equal(result, df)
Example #26
Source File: test_ticks.py From recruit with Apache License 2.0 | 5 votes |
def test_tick_addition(kls, expected): offset = kls(3) result = offset + Timedelta(hours=2) assert isinstance(result, Timedelta) assert result == expected
Example #27
Source File: test_ticks.py From recruit with Apache License 2.0 | 5 votes |
def test_delta_to_tick(): delta = timedelta(3) tick = offsets._delta_to_tick(delta) assert (tick == offsets.Day(3)) td = Timedelta(nanoseconds=5) tick = offsets._delta_to_tick(td) assert tick == Nano(5)
Example #28
Source File: test_frame.py From recruit with Apache License 2.0 | 5 votes |
def test_subplots_timeseries_y_axis(self): # GH16953 data = {"numeric": np.array([1, 2, 5]), "timedelta": [pd.Timedelta(-10, unit="s"), pd.Timedelta(10, unit="m"), pd.Timedelta(10, unit="h")], "datetime_no_tz": [pd.to_datetime("2017-08-01 00:00:00"), pd.to_datetime("2017-08-01 02:00:00"), pd.to_datetime("2017-08-02 00:00:00")], "datetime_all_tz": [pd.to_datetime("2017-08-01 00:00:00", utc=True), pd.to_datetime("2017-08-01 02:00:00", utc=True), pd.to_datetime("2017-08-02 00:00:00", utc=True)], "text": ["This", "should", "fail"]} testdata = DataFrame(data) ax_numeric = testdata.plot(y="numeric") assert (ax_numeric.get_lines()[0].get_data()[1] == testdata["numeric"].values).all() ax_timedelta = testdata.plot(y="timedelta") assert (ax_timedelta.get_lines()[0].get_data()[1] == testdata["timedelta"].values).all() ax_datetime_no_tz = testdata.plot(y="datetime_no_tz") assert (ax_datetime_no_tz.get_lines()[0].get_data()[1] == testdata["datetime_no_tz"].values).all() ax_datetime_all_tz = testdata.plot(y="datetime_all_tz") assert (ax_datetime_all_tz.get_lines()[0].get_data()[1] == testdata["datetime_all_tz"].values).all() with pytest.raises(TypeError): testdata.plot(y="text")
Example #29
Source File: test_merge_asof.py From recruit with Apache License 2.0 | 5 votes |
def test_allow_exact_matches_and_tolerance2(self): # GH 13695 df1 = pd.DataFrame({ 'time': pd.to_datetime(['2016-07-15 13:30:00.030']), 'username': ['bob']}) df2 = pd.DataFrame({ 'time': pd.to_datetime(['2016-07-15 13:30:00.000', '2016-07-15 13:30:00.030']), 'version': [1, 2]}) result = pd.merge_asof(df1, df2, on='time') expected = pd.DataFrame({ 'time': pd.to_datetime(['2016-07-15 13:30:00.030']), 'username': ['bob'], 'version': [2]}) assert_frame_equal(result, expected) result = pd.merge_asof(df1, df2, on='time', allow_exact_matches=False) expected = pd.DataFrame({ 'time': pd.to_datetime(['2016-07-15 13:30:00.030']), 'username': ['bob'], 'version': [1]}) assert_frame_equal(result, expected) result = pd.merge_asof(df1, df2, on='time', allow_exact_matches=False, tolerance=pd.Timedelta('10ms')) expected = pd.DataFrame({ 'time': pd.to_datetime(['2016-07-15 13:30:00.030']), 'username': ['bob'], 'version': [np.nan]}) assert_frame_equal(result, expected)
Example #30
Source File: test_merge_asof.py From recruit with Apache License 2.0 | 5 votes |
def test_allow_exact_matches_and_tolerance(self): result = merge_asof(self.trades, self.quotes, on='time', by='ticker', tolerance=Timedelta('100ms'), allow_exact_matches=False) expected = self.allow_exact_matches_and_tolerance assert_frame_equal(result, expected)