test_formats.py 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. import numpy as np
  2. import pytest
  3. from pandas import (
  4. DataFrame,
  5. Index,
  6. Interval,
  7. IntervalIndex,
  8. Series,
  9. Timedelta,
  10. Timestamp,
  11. )
  12. import pandas._testing as tm
  13. class TestIntervalIndexRendering:
  14. def test_frame_repr(self):
  15. # https://github.com/pandas-dev/pandas/pull/24134/files
  16. df = DataFrame(
  17. {"A": [1, 2, 3, 4]}, index=IntervalIndex.from_breaks([0, 1, 2, 3, 4])
  18. )
  19. result = repr(df)
  20. expected = " A\n(0, 1] 1\n(1, 2] 2\n(2, 3] 3\n(3, 4] 4"
  21. assert result == expected
  22. @pytest.mark.parametrize(
  23. "constructor,expected",
  24. [
  25. (
  26. Series,
  27. (
  28. "(0.0, 1.0] a\n"
  29. "NaN b\n"
  30. "(2.0, 3.0] c\n"
  31. "dtype: object"
  32. ),
  33. ),
  34. (DataFrame, (" 0\n(0.0, 1.0] a\nNaN b\n(2.0, 3.0] c")),
  35. ],
  36. )
  37. def test_repr_missing(self, constructor, expected):
  38. # GH 25984
  39. index = IntervalIndex.from_tuples([(0, 1), np.nan, (2, 3)])
  40. obj = constructor(list("abc"), index=index)
  41. result = repr(obj)
  42. assert result == expected
  43. def test_repr_floats(self):
  44. # GH 32553
  45. markers = Series(
  46. ["foo", "bar"],
  47. index=IntervalIndex(
  48. [
  49. Interval(left, right)
  50. for left, right in zip(
  51. Index([329.973, 345.137], dtype="float64"),
  52. Index([345.137, 360.191], dtype="float64"),
  53. )
  54. ]
  55. ),
  56. )
  57. result = str(markers)
  58. expected = "(329.973, 345.137] foo\n(345.137, 360.191] bar\ndtype: object"
  59. assert result == expected
  60. @pytest.mark.parametrize(
  61. "tuples, closed, expected_data",
  62. [
  63. ([(0, 1), (1, 2), (2, 3)], "left", ["[0, 1)", "[1, 2)", "[2, 3)"]),
  64. (
  65. [(0.5, 1.0), np.nan, (2.0, 3.0)],
  66. "right",
  67. ["(0.5, 1.0]", "NaN", "(2.0, 3.0]"],
  68. ),
  69. (
  70. [
  71. (Timestamp("20180101"), Timestamp("20180102")),
  72. np.nan,
  73. ((Timestamp("20180102"), Timestamp("20180103"))),
  74. ],
  75. "both",
  76. ["[2018-01-01, 2018-01-02]", "NaN", "[2018-01-02, 2018-01-03]"],
  77. ),
  78. (
  79. [
  80. (Timedelta("0 days"), Timedelta("1 days")),
  81. (Timedelta("1 days"), Timedelta("2 days")),
  82. np.nan,
  83. ],
  84. "neither",
  85. [
  86. "(0 days 00:00:00, 1 days 00:00:00)",
  87. "(1 days 00:00:00, 2 days 00:00:00)",
  88. "NaN",
  89. ],
  90. ),
  91. ],
  92. )
  93. def test_to_native_types(self, tuples, closed, expected_data):
  94. # GH 28210
  95. index = IntervalIndex.from_tuples(tuples, closed=closed)
  96. result = index._format_native_types()
  97. expected = np.array(expected_data)
  98. tm.assert_numpy_array_equal(result, expected)