test_interval.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. # -*- coding: utf-8 -*-
  2. import numpy as np
  3. import pytest
  4. import pandas as pd
  5. from pandas import Index, Interval, IntervalIndex, date_range, timedelta_range
  6. from pandas.core.arrays import IntervalArray
  7. import pandas.util.testing as tm
  8. @pytest.fixture(params=[
  9. (Index([0, 2, 4]), Index([1, 3, 5])),
  10. (Index([0., 1., 2.]), Index([1., 2., 3.])),
  11. (timedelta_range('0 days', periods=3),
  12. timedelta_range('1 day', periods=3)),
  13. (date_range('20170101', periods=3), date_range('20170102', periods=3)),
  14. (date_range('20170101', periods=3, tz='US/Eastern'),
  15. date_range('20170102', periods=3, tz='US/Eastern'))],
  16. ids=lambda x: str(x[0].dtype))
  17. def left_right_dtypes(request):
  18. """
  19. Fixture for building an IntervalArray from various dtypes
  20. """
  21. return request.param
  22. class TestMethods(object):
  23. @pytest.mark.parametrize('new_closed', [
  24. 'left', 'right', 'both', 'neither'])
  25. def test_set_closed(self, closed, new_closed):
  26. # GH 21670
  27. array = IntervalArray.from_breaks(range(10), closed=closed)
  28. result = array.set_closed(new_closed)
  29. expected = IntervalArray.from_breaks(range(10), closed=new_closed)
  30. tm.assert_extension_array_equal(result, expected)
  31. @pytest.mark.parametrize('other', [
  32. Interval(0, 1, closed='right'),
  33. IntervalArray.from_breaks([1, 2, 3, 4], closed='right'),
  34. ])
  35. def test_where_raises(self, other):
  36. ser = pd.Series(IntervalArray.from_breaks([1, 2, 3, 4],
  37. closed='left'))
  38. match = "'value.closed' is 'right', expected 'left'."
  39. with pytest.raises(ValueError, match=match):
  40. ser.where([True, False, True], other=other)
  41. class TestSetitem(object):
  42. def test_set_na(self, left_right_dtypes):
  43. left, right = left_right_dtypes
  44. result = IntervalArray.from_arrays(left, right)
  45. result[0] = np.nan
  46. expected_left = Index([left._na_value] + list(left[1:]))
  47. expected_right = Index([right._na_value] + list(right[1:]))
  48. expected = IntervalArray.from_arrays(expected_left, expected_right)
  49. tm.assert_extension_array_equal(result, expected)
  50. def test_repr_matches():
  51. idx = IntervalIndex.from_breaks([1, 2, 3])
  52. a = repr(idx)
  53. b = repr(idx.values)
  54. assert a.replace("Index", "Array") == b