Repository: pandas-dev/pandas

Issue:
cannot output csv with IntervalIndex
#### Code Sample, a copy-pastable example if possible

Using `pd.interval_range`:
```python
pd.DataFrame({'a': [1, 2, 3]}, index=pd.interval_range(0, 1, periods=3)).to_csv('hello.csv')
```

Using `pd.IntervalIndex.from_arrays`:
```python
pd.DataFrame({'a': [1, 2, 3]}, index=pd.IntervalIndex.from_arrays(np.array([0, 1, 2]), np.array([1, 2, 3]))).to_csv('hello.csv')
```

#### Problem description

```
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-2-6f913f6c0211> in <module>
----> 1 pd.DataFrame({'a': [1, 2, 3]}, index=pd.IntervalIndex.from_arrays(np.array([0, 1, 2]), np.array([1, 2, 3]))).to_csv('hello.csv')

~/Development/propensity-to-subscribe-modeling/.venv/lib/python3.7/site-packages/pandas/core/generic.py in to_csv(self, path_or_buf, sep, na_rep, float_format, columns, header, index, index_label, mode, encoding, compression, quoting, quotechar, line_terminator, chunksize, date_format, doublequote, escapechar, decimal)
   3226             decimal=decimal,
   3227         )
-> 3228         formatter.save()
   3229 
   3230         if path_or_buf is None:

~/Development/propensity-to-subscribe-modeling/.venv/lib/python3.7/site-packages/pandas/io/formats/csvs.py in save(self)
    200                 self.writer = UnicodeWriter(f, **writer_kwargs)
    201 
--> 202             self._save()
    203 
    204         finally:

~/Development/propensity-to-subscribe-modeling/.venv/lib/python3.7/site-packages/pandas/io/formats/csvs.py in _save(self)
    322                 break
    323 
--> 324             self._save_chunk(start_i, end_i)
    325 
    326     def _save_chunk(self, start_i, end_i):

~/Development/propensity-to-subscribe-modeling/.venv/lib/python3.7/site-packages/pandas/io/formats/csvs.py in _save_chunk(self, start_i, end_i)
    354         )
    355 
--> 356         libwriters.write_csv_rows(self.data, ix, self.nlevels, self.cols, self.writer)

TypeError: Argument 'data_index' has incorrect type (expected numpy.ndarray, got list)
```

#### Expected Output

#### Output of ``pd.show_versions()``

<details>

```
INSTALLED VERSIONS
------------------
commit           : None
python           : 3.7.4.final.0
python-bits      : 64
OS               : Darwin
OS-release       : 18.7.0
machine          : x86_64
processor        : i386
byteorder        : little
LC_ALL           : None
LANG             : en_US.UTF-8
LOCALE           : en_US.UTF-8

pandas           : 0.25.1
numpy            : 1.17.0
pytz             : 2019.2
dateutil         : 2.8.0
pip              : 19.2.2
setuptools       : 41.1.0
Cython           : None
pytest           : None
hypothesis       : None
sphinx           : None
blosc            : None
feather          : None
xlsxwriter       : None
lxml.etree       : None
html5lib         : None
pymysql          : None
psycopg2         : None
jinja2           : 2.10.1
IPython          : 7.7.0
pandas_datareader: None
bs4              : None
bottleneck       : None
fastparquet      : None
gcsfs            : None
lxml.etree       : None
matplotlib       : 3.1.1
numexpr          : None
odfpy            : None
openpyxl         : None
pandas_gbq       : None
pyarrow          : 0.14.1
pytables         : None
s3fs             : None
scipy            : 1.3.1
sqlalchemy       : None
tables           : None
xarray           : None
xlrd             : None
xlwt             : None
xlsxwriter       : None
```

</details>



Discussion:
Thanks, for the report.  I can confirm this behavior on master:
```python
In [2]: df = pd.DataFrame({'a': [1, 2, 3]}, index=pd.interval_range(0, 3))

In [3]: df.to_csv()
---------------------------------------------------------------------------
TypeError: Argument 'data_index' has incorrect type (expected numpy.ndarray, got list)
```

A temporary workaround is to cast the index to string prior to writing the output:
```python
In [4]: df.index = df.index.astype(str)

In [5]: df.to_csv()
Out[5]: ',a\n"(0, 1]",1\n"(1, 2]",2\n"(2, 3]",3\n'
```
In the example
```
import pandas

df = pandas.DataFrame({'a': [1, 2, 3]}, index=pandas.interval_range(0, 3))
```

is the expected output
```
',a\n"(0, 1]",1\n"(1, 2]",2\n"(2, 3]",3\n'
```

or is that just a temporary workaround to avoid an error?
I think the string representation would be fine as the expected output. If a user wants a non-string output they can break the IntervalIndex out into `index.left` and `index.right`.
Yes, that should be the expected output, or at the very least is consistent with previous versions where this was working:

```python
In [1]: import pandas as pd; pd.__version__
Out[1]: '0.23.4'

In [2]: df = pd.DataFrame({'a': [1, 2, 3]}, index=pd.interval_range(0, 3))

In [3]: df.to_csv()
Out[3]: ',a\n"(0, 1]",1\n"(1, 2]",2\n"(2, 3]",3\n
```

Note that my example produces string output because I didn't pass anything for `path_or_buf` in [`to_csv`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_csv.html), so the behavior in that case is to display a string of what would be written to a file.  Maybe not common knowledge but useful for debugging and the like.

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
@@ -1096,12 +1096,8 @@ def _format_with_header(self, header, **kwargs):
         return header + list(self._format_native_types(**kwargs))
 
     def _format_native_types(self, na_rep="NaN", quoting=None, **kwargs):
-        """ actually format my specific types """
-        from pandas.io.formats.format import ExtensionArrayFormatter
-
-        return ExtensionArrayFormatter(
-            values=self, na_rep=na_rep, justify="all", leading_space=False
-        ).get_result()
+        # GH 28210: use base method but with different default na_rep
+        return super()._format_native_types(na_rep=na_rep, quoting=quoting, **kwargs)
 
     def _format_data(self, name=None):
 


Test patch:
diff --git a/pandas/tests/frame/test_to_csv.py b/pandas/tests/frame/test_to_csv.py
--- a/pandas/tests/frame/test_to_csv.py
+++ b/pandas/tests/frame/test_to_csv.py
@@ -695,6 +695,20 @@ def _make_frame(names=None):
             tm.assert_index_equal(recons.columns, exp.columns)
             assert len(recons) == 0
 
+    def test_to_csv_interval_index(self):
+        # GH 28210
+        df = DataFrame({"A": list("abc"), "B": range(3)}, index=pd.interval_range(0, 3))
+
+        with ensure_clean("__tmp_to_csv_interval_index__.csv") as path:
+            df.to_csv(path)
+            result = self.read_csv(path, index_col=0)
+
+            # can't roundtrip intervalindex via read_csv so check string repr (GH 23595)
+            expected = df.copy()
+            expected.index = expected.index.astype(str)
+
+            assert_frame_equal(result, expected)
+
     def test_to_csv_float32_nanrep(self):
         df = DataFrame(np.random.randn(1, 4).astype(np.float32))
         df[1] = np.nan
diff --git a/pandas/tests/indexes/interval/test_interval.py b/pandas/tests/indexes/interval/test_interval.py
--- a/pandas/tests/indexes/interval/test_interval.py
+++ b/pandas/tests/indexes/interval/test_interval.py
@@ -417,6 +417,46 @@ def test_repr_missing(self, constructor, expected):
         result = repr(obj)
         assert result == expected
 
+    @pytest.mark.parametrize(
+        "tuples, closed, expected_data",
+        [
+            ([(0, 1), (1, 2), (2, 3)], "left", ["[0, 1)", "[1, 2)", "[2, 3)"]),
+            (
+                [(0.5, 1.0), np.nan, (2.0, 3.0)],
+                "right",
+                ["(0.5, 1.0]", "NaN", "(2.0, 3.0]"],
+            ),
+            (
+                [
+                    (Timestamp("20180101"), Timestamp("20180102")),
+                    np.nan,
+                    ((Timestamp("20180102"), Timestamp("20180103"))),
+                ],
+                "both",
+                ["[2018-01-01, 2018-01-02]", "NaN", "[2018-01-02, 2018-01-03]"],
+            ),
+            (
+                [
+                    (Timedelta("0 days"), Timedelta("1 days")),
+                    (Timedelta("1 days"), Timedelta("2 days")),
+                    np.nan,
+                ],
+                "neither",
+                [
+                    "(0 days 00:00:00, 1 days 00:00:00)",
+                    "(1 days 00:00:00, 2 days 00:00:00)",
+                    "NaN",
+                ],
+            ),
+        ],
+    )
+    def test_to_native_types(self, tuples, closed, expected_data):
+        # GH 28210
+        index = IntervalIndex.from_tuples(tuples, closed=closed)
+        result = index.to_native_types()
+        expected = np.array(expected_data)
+        tm.assert_numpy_array_equal(result, expected)
+
     def test_get_item(self, closed):
         i = IntervalIndex.from_arrays((0, 1, np.nan), (1, 2, np.nan), closed=closed)
         assert i[0] == Interval(0.0, 1.0, closed=closed)
diff --git a/pandas/tests/series/test_io.py b/pandas/tests/series/test_io.py
--- a/pandas/tests/series/test_io.py
+++ b/pandas/tests/series/test_io.py
@@ -191,6 +191,20 @@ def test_to_csv_compression(self, s, encoding, compression):
                     s, pd.read_csv(fh, index_col=0, squeeze=True, encoding=encoding)
                 )
 
+    def test_to_csv_interval_index(self):
+        # GH 28210
+        s = Series(["foo", "bar", "baz"], index=pd.interval_range(0, 3))
+
+        with ensure_clean("__tmp_to_csv_interval_index__.csv") as path:
+            s.to_csv(path, header=False)
+            result = self.read_csv(path, index_col=0, squeeze=True)
+
+            # can't roundtrip intervalindex via read_csv so check string repr (GH 23595)
+            expected = s.copy()
+            expected.index = expected.index.astype(str)
+
+            assert_series_equal(result, expected)
+
 
 class TestSeriesIO:
     def test_to_frame(self, datetime_series):