Skip to content

Fix to_csv of DataFrame with single level multiindex. #19831

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 1, 2018
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
3 changes: 2 additions & 1 deletion doc/source/whatsnew/v0.24.0.txt
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ Renaming names in a MultiIndex
:func:`DataFrame.rename_axis` now supports ``index`` and ``columns`` arguments
and :func:`Series.rename_axis` supports ``index`` argument (:issue:`19978`)

This change allows a dictionary to be passed so that some of the names
This change allows a dictionary to be passed so that some of the names
of a ``MultiIndex`` can be changed.

Example:
Expand Down Expand Up @@ -1216,6 +1216,7 @@ Notice how we now instead output ``np.nan`` itself instead of a stringified form
- :func:`read_sas()` will correctly parse sas7bdat files with data page types having also bit 7 set (so page type is 128 + 256 = 384) (:issue:`16615`)
- Bug in :meth:`detect_client_encoding` where potential ``IOError`` goes unhandled when importing in a mod_wsgi process due to restricted access to stdout. (:issue:`21552`)
- Bug in :func:`to_string()` that broke column alignment when ``index=False`` and width of first column's values is greater than the width of first column's header (:issue:`16839`, :issue:`13032`)
- Bug in :func:`DataFrame.to_csv` where a single level MultiIndex incorrectly wrote a tuple. Now just the value of the index is written (:issue:`19589`).

Plotting
^^^^^^^^
Expand Down
13 changes: 8 additions & 5 deletions pandas/core/indexes/multi.py
Original file line number Diff line number Diff line change
Expand Up @@ -732,11 +732,14 @@ def _format_native_types(self, na_rep='nan', **kwargs):
new_levels.append(level)
new_labels.append(label)

# reconstruct the multi-index
mi = MultiIndex(levels=new_levels, labels=new_labels, names=self.names,
sortorder=self.sortorder, verify_integrity=False)

return mi.values
if len(new_levels) == 1:
return Index(new_levels[0])._format_native_types()
else:
# reconstruct the multi-index
mi = MultiIndex(levels=new_levels, labels=new_labels,
names=self.names, sortorder=self.sortorder,
verify_integrity=False)
return mi.values

@Appender(_index_shared_docs['_get_grouper_for_level'])
def _get_grouper_for_level(self, mapper, level):
Expand Down
19 changes: 19 additions & 0 deletions pandas/tests/io/formats/test_to_csv.py
Original file line number Diff line number Diff line change
Expand Up @@ -325,6 +325,25 @@ def test_to_csv_multi_index(self):
exp = tm.convert_rows_list_to_csv_str(exp_rows)
assert df.to_csv(index=False) == exp

@pytest.mark.parametrize("ind,expected", [
(pd.MultiIndex(levels=[[1.0]],
labels=[[0]],
names=["x"]),
"x,data\n1.0,1\n"),
(pd.MultiIndex(levels=[[1.], [2.]],
labels=[[0], [0]],
names=["x", "y"]),
"x,y,data\n1.0,2.0,1\n")
])
@pytest.mark.parametrize("klass", [
pd.DataFrame, pd.Series
])
def test_to_csv_single_level_multi_index(self, ind, expected, klass):
# see gh-19589
result = klass(pd.Series([1], ind, name="data")).to_csv(
line_terminator="\n", header=True)
assert result == expected

def test_to_csv_string_array_ascii(self):
# GH 10813
str_array = [{'names': ['foo', 'bar']}, {'names': ['baz', 'qux']}]
Expand Down