Repository: pandas-dev/pandas

Issue:
IntervalIndex.from_arrays/from_breaks does not accept categorical data with valid dtype
xref #21243

#### Code Sample, a copy-pastable example if possible
`IntervalIndex.from_arrays` fails:
```python
In [2]: cat_l = pd.Categorical([0, 0, 1, 2, 2])

In [3]: cat_r = pd.Categorical([1, 3, 3, 3, 4])

In [4]: pd.IntervalIndex.from_arrays(cat_l, cat_r)
---------------------------------------------------------------------------
TypeError: category, object, and string subtypes are not supported for IntervalIndex
```

`IntervalIndex.from_breaks` fails:
```python
In [5]: cat_breaks = pd.Categorical([0, 1, 2, 3])

In [6]: pd.IntervalIndex.from_breaks(cat_breaks)
---------------------------------------------------------------------------
TypeError: category, object, and string subtypes are not supported for IntervalIndex
```

`IntervalIndex.from_tuples` currently works, though is likely not tested:
```python
In [7]: cat_tup = pd.Categorical([(0, 1), (0, 1), (0, 3), (1, 2)])

In [8]: pd.IntervalIndex.from_tuples(cat_tup)
Out[8]:
IntervalIndex([(0, 1], (0, 1], (0, 3], (1, 2]]
              closed='right',
              dtype='interval[int64]')
```

`IntervalIndex.from_intervals` is deprecated, but will fail in the same way as described in #21243 since it hits the same code path.

The above examples also fail with `CategoricalIndex`.

Categorical data that is not of the appropriate dtype, e.g. strings, should still not be supported.

#### Problem description
An `IntervalIndex` cannot be created from categorical data with the appropriate dtype.  I doubt the failing examples shown above are very common, but #21243 seems like it'd be more common, and fixing it gives us this support for free.

#### Expected Output
I'd expect these to be successfully created (i.e. same result as building from the underlying list of data).

#### Output of ``pd.show_versions()``

<details>

INSTALLED VERSIONS
------------------
commit: c85ab083919b59ce84c220d5baf7d34ff4a0bcf2
python: 3.6.1.final.0
python-bits: 64
OS: Windows
OS-release: 10
machine: AMD64
processor: Intel64 Family 6 Model 78 Stepping 3, GenuineIntel
byteorder: little
LC_ALL: None
LANG: None
LOCALE: None.None

pandas: 0.24.0.dev0+42.gc85ab08
pytest: 3.1.2
pip: 9.0.1
setuptools: 39.0.1
Cython: 0.28.2
numpy: 1.13.3
scipy: 1.0.0
pyarrow: 0.6.0
xarray: 0.9.6
IPython: 6.1.0
sphinx: 1.5.6
patsy: 0.4.1
dateutil: 2.6.0
pytz: 2017.2
blosc: None
bottleneck: 1.2.1
tables: 3.4.2
numexpr: 2.6.4
feather: 0.4.0
matplotlib: 2.0.2
openpyxl: 2.4.8
xlrd: 1.1.0
xlwt: 1.3.0
xlsxwriter: 0.9.8
lxml: 3.8.0
bs4: None
html5lib: 0.999
sqlalchemy: 1.1.13
pymysql: None
psycopg2: None
jinja2: 2.9.6
s3fs: None
fastparquet: 0.1.5
pandas_gbq: None
pandas_datareader: None

</details>



Discussion:

Resolving patch:
diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py
--- a/pandas/core/indexes/interval.py
+++ b/pandas/core/indexes/interval.py
@@ -112,6 +112,10 @@ def maybe_convert_platform_interval(values):
     -------
     array
     """
+    if is_categorical_dtype(values):
+        # GH 21243/21253
+        values = np.array(values)
+
     if isinstance(values, (list, tuple)) and len(values) == 0:
         # GH 19016
         # empty lists/tuples get object dtype by default, but this is not


Test patch:
diff --git a/pandas/tests/indexes/interval/test_construction.py b/pandas/tests/indexes/interval/test_construction.py
--- a/pandas/tests/indexes/interval/test_construction.py
+++ b/pandas/tests/indexes/interval/test_construction.py
@@ -6,8 +6,9 @@
 
 from pandas import (
     Interval, IntervalIndex, Index, Int64Index, Float64Index, Categorical,
-    date_range, timedelta_range, period_range, notna)
+    CategoricalIndex, date_range, timedelta_range, period_range, notna)
 from pandas.compat import lzip
+from pandas.core.dtypes.common import is_categorical_dtype
 from pandas.core.dtypes.dtypes import IntervalDtype
 import pandas.core.common as com
 import pandas.util.testing as tm
@@ -111,6 +112,22 @@ def test_constructor_string(self, constructor, breaks):
         with tm.assert_raises_regex(TypeError, msg):
             constructor(**self.get_kwargs_from_breaks(breaks))
 
+    @pytest.mark.parametrize('cat_constructor', [
+        Categorical, CategoricalIndex])
+    def test_constructor_categorical_valid(self, constructor, cat_constructor):
+        # GH 21243/21253
+        if isinstance(constructor, partial) and constructor.func is Index:
+            # Index is defined to create CategoricalIndex from categorical data
+            pytest.skip()
+
+        breaks = np.arange(10, dtype='int64')
+        expected = IntervalIndex.from_breaks(breaks)
+
+        cat_breaks = cat_constructor(breaks)
+        result_kwargs = self.get_kwargs_from_breaks(cat_breaks)
+        result = constructor(**result_kwargs)
+        tm.assert_index_equal(result, expected)
+
     def test_generic_errors(self, constructor):
         # filler input data to be used when supplying invalid kwargs
         filler = self.get_kwargs_from_breaks(range(10))
@@ -238,6 +255,8 @@ def get_kwargs_from_breaks(self, breaks, closed='right'):
         tuples = lzip(breaks[:-1], breaks[1:])
         if isinstance(breaks, (list, tuple)):
             return {'data': tuples}
+        elif is_categorical_dtype(breaks):
+            return {'data': breaks._constructor(tuples)}
         return {'data': com._asarray_tuplesafe(tuples)}
 
     def test_constructor_errors(self):
@@ -286,6 +305,8 @@ def get_kwargs_from_breaks(self, breaks, closed='right'):
 
         if isinstance(breaks, list):
             return {'data': ivs}
+        elif is_categorical_dtype(breaks):
+            return {'data': breaks._constructor(ivs)}
         return {'data': np.array(ivs, dtype=object)}
 
     def test_generic_errors(self, constructor):