Skip to content

Commit

Permalink
BUG: Fix MultiIndex DataFrame to_csv() segfault
Browse files Browse the repository at this point in the history
  • Loading branch information
Matias Heikkilä committed May 12, 2019
1 parent 17247ed commit c5d36b9
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 1 deletion.
1 change: 1 addition & 0 deletions doc/source/whatsnew/v0.25.0.rst
Expand Up @@ -254,6 +254,7 @@ Performance Improvements
- Improved performance of :meth:`Series.map` for dictionary mappers on categorical series by mapping the categories instead of mapping all values (:issue:`23785`)

.. _whatsnew_0250.bug_fixes:
- Fixed MultiIndex DataFrame to_csv segfault (:issue:`26303`)

Bug Fixes
~~~~~~~~~
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/indexes/multi.py
Expand Up @@ -946,7 +946,7 @@ 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()
return Index(new_levels[0][new_codes[0]])._format_native_types()
else:
# reconstruct the multi-index
mi = MultiIndex(levels=new_levels, codes=new_codes,
Expand Down
12 changes: 12 additions & 0 deletions pandas/tests/frame/test_to_csv.py
Expand Up @@ -874,6 +874,18 @@ def test_to_csv_index_no_leading_comma(self):
expected = tm.convert_rows_list_to_csv_str(expected_rows)
assert buf.getvalue() == expected

def test_to_csv_multi_index(self):
# see gh-26303
index = pd.Index([(1,), (2,), (3,)])
df = pd.DataFrame([[1, 2, 3]], columns=index)
with ensure_clean() as path:
df = df.reindex(columns=[(1,), (3,)])
df.to_csv(path, line_terminator='\n')
expected = b",1,3\n0,1,3\n"

with open(path, mode='rb') as f:
assert f.read() == expected

def test_to_csv_line_terminators(self):
# see gh-20353
df = DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]},
Expand Down

0 comments on commit c5d36b9

Please sign in to comment.