Skip to content

Commit c5d36b9

Browse files
author
Matias Heikkilä
committed
BUG: Fix MultiIndex DataFrame to_csv() segfault
1 parent 17247ed commit c5d36b9

File tree

3 files changed

+14
-1
lines changed

3 files changed

+14
-1
lines changed

doc/source/whatsnew/v0.25.0.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -254,6 +254,7 @@ Performance Improvements
254254
- Improved performance of :meth:`Series.map` for dictionary mappers on categorical series by mapping the categories instead of mapping all values (:issue:`23785`)
255255

256256
.. _whatsnew_0250.bug_fixes:
257+
- Fixed MultiIndex DataFrame to_csv segfault (:issue:`26303`)
257258

258259
Bug Fixes
259260
~~~~~~~~~

pandas/core/indexes/multi.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -946,7 +946,7 @@ def _format_native_types(self, na_rep='nan', **kwargs):
946946
new_codes.append(level_codes)
947947

948948
if len(new_levels) == 1:
949-
return Index(new_levels[0])._format_native_types()
949+
return Index(new_levels[0][new_codes[0]])._format_native_types()
950950
else:
951951
# reconstruct the multi-index
952952
mi = MultiIndex(levels=new_levels, codes=new_codes,

pandas/tests/frame/test_to_csv.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -874,6 +874,18 @@ def test_to_csv_index_no_leading_comma(self):
874874
expected = tm.convert_rows_list_to_csv_str(expected_rows)
875875
assert buf.getvalue() == expected
876876

877+
def test_to_csv_multi_index(self):
878+
# see gh-26303
879+
index = pd.Index([(1,), (2,), (3,)])
880+
df = pd.DataFrame([[1, 2, 3]], columns=index)
881+
with ensure_clean() as path:
882+
df = df.reindex(columns=[(1,), (3,)])
883+
df.to_csv(path, line_terminator='\n')
884+
expected = b",1,3\n0,1,3\n"
885+
886+
with open(path, mode='rb') as f:
887+
assert f.read() == expected
888+
877889
def test_to_csv_line_terminators(self):
878890
# see gh-20353
879891
df = DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]},

0 commit comments

Comments
 (0)