Skip to content

Commit e1f3a70

Browse files
authored
BUG: Override mi-columns in to_csv if requested (pandas-dev#18110)
Previously, MultiIndex columns weren't being overwritten when header was passed in for to_csv. Closes pandas-devgh-5539
1 parent 8388a47 commit e1f3a70

File tree

3 files changed

+15
-1
lines changed

3 files changed

+15
-1
lines changed

doc/source/whatsnew/v0.21.1.txt

+1
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,7 @@ I/O
7979

8080
- Bug in class:`~pandas.io.stata.StataReader` not converting date/time columns with display formatting addressed (:issue:`17990`). Previously columns with display formatting were normally left as ordinal numbers and not converted to datetime objects.
8181
- Bug in :func:`read_csv` when reading a compressed UTF-16 encoded file (:issue:`18071`)
82+
- Bug in :meth:`DataFrame.to_csv` when the table had ``MultiIndex`` columns, and a list of strings was passed in for ``header`` (:issue:`5539`)
8283

8384
Plotting
8485
^^^^^^^^

pandas/io/formats/format.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1695,7 +1695,7 @@ def _save_header(self):
16951695
else:
16961696
encoded_labels = []
16971697

1698-
if not has_mi_columns:
1698+
if not has_mi_columns or has_aliases:
16991699
encoded_labels += list(write_cols)
17001700
writer.writerow(encoded_labels)
17011701
else:

pandas/tests/frame/test_to_csv.py

+13
Original file line numberDiff line numberDiff line change
@@ -1203,3 +1203,16 @@ def test_period_index_date_overflow(self):
12031203

12041204
expected = ',0\n1990-01-01,4\n,5\n3005-01-01,6\n'
12051205
assert result == expected
1206+
1207+
def test_multi_index_header(self):
1208+
# see gh-5539
1209+
columns = pd.MultiIndex.from_tuples([("a", 1), ("a", 2),
1210+
("b", 1), ("b", 2)])
1211+
df = pd.DataFrame([[1, 2, 3, 4], [5, 6, 7, 8]])
1212+
df.columns = columns
1213+
1214+
header = ["a", "b", "c", "d"]
1215+
result = df.to_csv(header=header)
1216+
1217+
expected = ",a,b,c,d\n0,1,2,3,4\n1,5,6,7,8\n"
1218+
assert result == expected

0 commit comments

Comments
 (0)