Skip to content

BUG: Override mi-columns in to_csv if requested #18110

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 5, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/source/whatsnew/v0.21.1.txt
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ I/O

- 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.
- Bug in :func:`read_csv` when reading a compressed UTF-16 encoded file (:issue:`18071`)
- Bug in :meth:`DataFrame.to_csv` when the table had ``MultiIndex`` columns, and a list of strings was passed in for ``header`` (:issue:`5539`)

Plotting
^^^^^^^^
Expand Down
2 changes: 1 addition & 1 deletion pandas/io/formats/format.py
Original file line number Diff line number Diff line change
Expand Up @@ -1695,7 +1695,7 @@ def _save_header(self):
else:
encoded_labels = []

if not has_mi_columns:
if not has_mi_columns or has_aliases:
encoded_labels += list(write_cols)
writer.writerow(encoded_labels)
else:
Expand Down
13 changes: 13 additions & 0 deletions pandas/tests/frame/test_to_csv.py
Original file line number Diff line number Diff line change
Expand Up @@ -1203,3 +1203,16 @@ def test_period_index_date_overflow(self):

expected = ',0\n1990-01-01,4\n,5\n3005-01-01,6\n'
assert result == expected

def test_multi_index_header(self):
# see gh-5539
columns = pd.MultiIndex.from_tuples([("a", 1), ("a", 2),
("b", 1), ("b", 2)])
df = pd.DataFrame([[1, 2, 3, 4], [5, 6, 7, 8]])
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like DataFrame and MultiIndex are already imported, so could remove the pd., if you feel that's cleaner/worth an edit.

df.columns = columns

header = ["a", "b", "c", "d"]
result = df.to_csv(header=header)

expected = ",a,b,c,d\n0,1,2,3,4\n1,5,6,7,8\n"
assert result == expected