test_scalar_compat.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. # -*- coding: utf-8 -*-
  2. """
  3. Tests for TimedeltaIndex methods behaving like their Timedelta counterparts
  4. """
  5. import numpy as np
  6. import pytest
  7. import pandas as pd
  8. from pandas import Index, Series, Timedelta, TimedeltaIndex, timedelta_range
  9. import pandas.util.testing as tm
  10. class TestVectorizedTimedelta(object):
  11. def test_tdi_total_seconds(self):
  12. # GH#10939
  13. # test index
  14. rng = timedelta_range('1 days, 10:11:12.100123456', periods=2,
  15. freq='s')
  16. expt = [1 * 86400 + 10 * 3600 + 11 * 60 + 12 + 100123456. / 1e9,
  17. 1 * 86400 + 10 * 3600 + 11 * 60 + 13 + 100123456. / 1e9]
  18. tm.assert_almost_equal(rng.total_seconds(), Index(expt))
  19. # test Series
  20. ser = Series(rng)
  21. s_expt = Series(expt, index=[0, 1])
  22. tm.assert_series_equal(ser.dt.total_seconds(), s_expt)
  23. # with nat
  24. ser[1] = np.nan
  25. s_expt = Series([1 * 86400 + 10 * 3600 + 11 * 60 +
  26. 12 + 100123456. / 1e9, np.nan], index=[0, 1])
  27. tm.assert_series_equal(ser.dt.total_seconds(), s_expt)
  28. # with both nat
  29. ser = Series([np.nan, np.nan], dtype='timedelta64[ns]')
  30. tm.assert_series_equal(ser.dt.total_seconds(),
  31. Series([np.nan, np.nan], index=[0, 1]))
  32. def test_tdi_round(self):
  33. td = pd.timedelta_range(start='16801 days', periods=5, freq='30Min')
  34. elt = td[1]
  35. expected_rng = TimedeltaIndex([Timedelta('16801 days 00:00:00'),
  36. Timedelta('16801 days 00:00:00'),
  37. Timedelta('16801 days 01:00:00'),
  38. Timedelta('16801 days 02:00:00'),
  39. Timedelta('16801 days 02:00:00')])
  40. expected_elt = expected_rng[1]
  41. tm.assert_index_equal(td.round(freq='H'), expected_rng)
  42. assert elt.round(freq='H') == expected_elt
  43. msg = pd._libs.tslibs.frequencies.INVALID_FREQ_ERR_MSG
  44. with pytest.raises(ValueError, match=msg):
  45. td.round(freq='foo')
  46. with pytest.raises(ValueError, match=msg):
  47. elt.round(freq='foo')
  48. msg = "<MonthEnd> is a non-fixed frequency"
  49. with pytest.raises(ValueError, match=msg):
  50. td.round(freq='M')
  51. with pytest.raises(ValueError, match=msg):
  52. elt.round(freq='M')