Repository: pandas-dev/pandas

Issue:
MultiIndex DataFrame to_csv() terminates python process
#### Code Sample, a copy-pastable example if possible

```python
import traceback
import pandas as pd

# index is actually a MultiIndex
index = pd.Index([(1,), (2,), (3,)])
data = pd.DataFrame([[1, 2, 3]], columns=index)
data = data.reindex(columns=[(1,), (3,)])

try:
    # This call fails with a TypeError.
    data.to_csv('crash.csv')
except TypeError as err:
    traceback.print_exc()

# This print seems to be essential to trigger an immediate crash of the process
# in the following .to_csv call. The crash happens also if the preceding
# try/except block is removed.
print(data)
data.to_csv('crash.csv')
```

#### Problem description

The python-code above shows two, maybe three errors.
(1) The first call to DataFrame.to_csv raises a TypeError. This it uninformative at best. Printing the DataFrame works, so it should be possible to export it to csv. 
(2) The second call to DataFrame.to_csv leads to terminating python with exit code -1073741819 (0xC0000005). 
(3) It seems that the print call triggers this crash, even though I would expect a print to not alter the printed data structure.

The Windows event log shows an error happened in lib\site-packages\pandas\_libs\writers.cp36-win_amd64.pyd.

#### Expected Output

Because the DataFrame is printable on the console, I would expect a successful call of to_csv().

#### Output of ``pd.show_versions()``

<details>
Python Version: Python 3.6.6 (v3.6.6:4cf1f54eb7, Jun 27 2018, 03:37:03) [MSC v.1900 64 bit (AMD64)] on win32


INSTALLED VERSIONS
------------------
commit: None
python: 3.6.6.final.0
python-bits: 64
OS: Windows
OS-release: 7
machine: AMD64
processor: Intel64 Family 6 Model 60 Stepping 3, GenuineIntel
byteorder: little
LC_ALL: None
LANG: None
LOCALE: None.None

pandas: 0.24.2
pytest: None
pip: 10.0.1
setuptools: 39.1.0
Cython: None
numpy: 1.15.4
scipy: 1.2.0
pyarrow: None
xarray: None
IPython: 7.0.1
sphinx: None
patsy: None
dateutil: 2.7.5
pytz: 2018.7
blosc: None
bottleneck: None
tables: None
numexpr: None
feather: None
matplotlib: None
openpyxl: 2.6.1
xlrd: 1.2.0
xlwt: None
xlsxwriter: None
lxml.etree: 4.3.0
bs4: None
html5lib: None
sqlalchemy: None
pymysql: None
psycopg2: None
jinja2: 2.10
s3fs: None
fastparquet: None
pandas_gbq: None
pandas_datareader: None
gcsfs: None


</details>



Discussion:
Strange indeed, though this segfaulted for me during the try...except block. 

Investigation and PRs are always welcome!
I will do this. Assign it to me please.

Resolving patch:
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py
--- a/pandas/core/indexes/multi.py
+++ b/pandas/core/indexes/multi.py
@@ -946,7 +946,9 @@ def _format_native_types(self, na_rep='nan', **kwargs):
             new_codes.append(level_codes)
 
         if len(new_levels) == 1:
-            return Index(new_levels[0])._format_native_types()
+            # a single-level multi-index
+            return Index(new_levels[0].take(
+                new_codes[0]))._format_native_types()
         else:
             # reconstruct the multi-index
             mi = MultiIndex(levels=new_levels, codes=new_codes,


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
@@ -1220,6 +1220,15 @@ def test_multi_index_header(self):
         expected = tm.convert_rows_list_to_csv_str(expected_rows)
         assert result == expected
 
+    def test_to_csv_single_level_multi_index(self):
+        # see gh-26303
+        index = pd.Index([(1,), (2,), (3,)])
+        df = pd.DataFrame([[1, 2, 3]], columns=index)
+        df = df.reindex(columns=[(1,), (3,)])
+        expected = ",1,3\n0,1,3\n"
+        result = df.to_csv(line_terminator='\n')
+        assert_almost_equal(result, expected)
+
     def test_gz_lineend(self):
         # GH 25311
         df = pd.DataFrame({'a': [1, 2]})