Repository: pandas-dev/pandas

Issue:
BUG: IntervalIndex.to_tuples doesn't handle NA correctly
#### Code Sample, a copy-pastable example if possible

```python
In [2]: idx = pd.interval_range(0, 3).insert(0, np.nan)
   ...: idx
   ...:
Out[2]:
IntervalIndex([nan, (0.0, 1.0], (1.0, 2.0], (2.0, 3.0]]
              closed='right',
              dtype='interval[float64]')

In [3]: idx.to_tuples()
Out[3]: Index([(nan, nan), (0.0, 1.0), (1.0, 2.0), (2.0, 3.0)], dtype='object')
```
#### Problem description
A tuple of `np.nan` is returned instead of just `np.nan`.  Note that `values` and `tolist` both yield `np.nan`:

```python
In [4]: idx.values
Out[4]:
array([nan, Interval(0.0, 1.0, closed='right'),
       Interval(1.0, 2.0, closed='right'),
       Interval(2.0, 3.0, closed='right')], dtype=object)

In [5]: idx.tolist()
Out[5]:
[nan,
 Interval(0.0, 1.0, closed='right'),
 Interval(1.0, 2.0, closed='right'),
 Interval(2.0, 3.0, closed='right')]
```

#### Expected Output
`np.nan` instead of a tuple of `np.nan`:
```python
Index([nan, (0.0, 1.0), (1.0, 2.0), (2.0, 3.0)], dtype='object')
```

#### Output of ``pd.show_versions()``

<details>

INSTALLED VERSIONS
------------------
commit: d2fd22e1f995a638f1e84b0ef091eaf70e171fdc
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.22.0.dev0+353.gd2fd22e
pytest: 3.1.2
pip: 9.0.1
setuptools: 27.2.0
Cython: 0.25.2
numpy: 1.13.1
scipy: 0.19.1
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: None
tables: 3.4.2
numexpr: 2.6.2
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.0
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
@@ -544,9 +544,31 @@ def from_tuples(cls, data, closed='right', name=None, copy=False):
 
         return cls.from_arrays(left, right, closed, name=name, copy=False)
 
-    def to_tuples(self):
-        """Return an Index of tuples of the form (left, right)"""
-        return Index(_asarray_tuplesafe(zip(self.left, self.right)))
+    def to_tuples(self, na_tuple=True):
+        """
+        Return an Index of tuples of the form (left, right)
+
+        Parameters
+        ----------
+        na_tuple : boolean, default True
+            Returns NA as a tuple if True, ``(nan, nan)``, or just as the NA
+            value itself if False, ``nan``.
+
+            ..versionadded:: 0.22.0
+
+        Examples
+        --------
+        >>>  idx = pd.IntervalIndex.from_arrays([0, np.nan, 2], [1, np.nan, 3])
+        >>>  idx.to_tuples()
+        Index([(0.0, 1.0), (nan, nan), (2.0, 3.0)], dtype='object')
+        >>>  idx.to_tuples(na_tuple=False)
+        Index([(0.0, 1.0), nan, (2.0, 3.0)], dtype='object')
+        """
+        tuples = _asarray_tuplesafe(zip(self.left, self.right))
+        if not na_tuple:
+            # GH 18756
+            tuples = np.where(~self._isnan, tuples, np.nan)
+        return Index(tuples)
 
     @cache_readonly
     def _multiindex(self):


Test patch:
diff --git a/pandas/tests/indexes/test_interval.py b/pandas/tests/indexes/test_interval.py
--- a/pandas/tests/indexes/test_interval.py
+++ b/pandas/tests/indexes/test_interval.py
@@ -7,6 +7,7 @@
     Interval, IntervalIndex, Index, isna, notna, interval_range, Timestamp,
     Timedelta, compat, date_range, timedelta_range, DateOffset)
 from pandas.compat import lzip
+from pandas.core.common import _asarray_tuplesafe
 from pandas.tseries.offsets import Day
 from pandas._libs.interval import IntervalTree
 from pandas.tests.indexes.common import Base
@@ -1072,6 +1073,45 @@ def test_is_non_overlapping_monotonic(self, closed):
             idx = IntervalIndex.from_breaks(range(4), closed=closed)
             assert idx.is_non_overlapping_monotonic is True
 
+    @pytest.mark.parametrize('tuples', [
+        lzip(range(10), range(1, 11)),
+        lzip(date_range('20170101', periods=10),
+             date_range('20170101', periods=10)),
+        lzip(timedelta_range('0 days', periods=10),
+             timedelta_range('1 day', periods=10))])
+    def test_to_tuples(self, tuples):
+        # GH 18756
+        idx = IntervalIndex.from_tuples(tuples)
+        result = idx.to_tuples()
+        expected = Index(_asarray_tuplesafe(tuples))
+        tm.assert_index_equal(result, expected)
+
+    @pytest.mark.parametrize('tuples', [
+        lzip(range(10), range(1, 11)) + [np.nan],
+        lzip(date_range('20170101', periods=10),
+             date_range('20170101', periods=10)) + [np.nan],
+        lzip(timedelta_range('0 days', periods=10),
+             timedelta_range('1 day', periods=10)) + [np.nan]])
+    @pytest.mark.parametrize('na_tuple', [True, False])
+    def test_to_tuples_na(self, tuples, na_tuple):
+        # GH 18756
+        idx = IntervalIndex.from_tuples(tuples)
+        result = idx.to_tuples(na_tuple=na_tuple)
+
+        # check the non-NA portion
+        expected_notna = Index(_asarray_tuplesafe(tuples[:-1]))
+        result_notna = result[:-1]
+        tm.assert_index_equal(result_notna, expected_notna)
+
+        # check the NA portion
+        result_na = result[-1]
+        if na_tuple:
+            assert isinstance(result_na, tuple)
+            assert len(result_na) == 2
+            assert all(isna(x) for x in result_na)
+        else:
+            assert isna(result_na)
+
 
 class TestIntervalRange(object):