diff --git a/doc/source/release.rst b/doc/source/release.rst index 6d8f915e2ebb8..857a4d237f423 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -381,6 +381,8 @@ Bug Fixes - Bug in arithmetic operations affecting to NaT (:issue:`6873`) - Bug in ``Series.str.extract`` where the resulting ``Series`` from a single group match wasn't renamed to the group name +- Bug in ``DataFrame.to_csv`` where setting `index` to `False` ignored the + `header` kwarg (:issue:`6186`) pandas 0.13.1 ------------- diff --git a/pandas/core/format.py b/pandas/core/format.py index a7cbf2c70a5d3..117b686b02d75 100644 --- a/pandas/core/format.py +++ b/pandas/core/format.py @@ -1194,6 +1194,14 @@ def _save_header(self): has_aliases = isinstance(header, (tuple, list, np.ndarray)) if not (has_aliases or self.header): return + if has_aliases: + if len(header) != len(cols): + raise ValueError(('Writing %d cols but got %d aliases' + % (len(cols), len(header)))) + else: + write_cols = header + else: + write_cols = cols if self.index: # should write something for index label @@ -1219,22 +1227,8 @@ def _save_header(self): else: encoded_labels = [] - if has_aliases: - if len(header) != len(cols): - raise ValueError(('Writing %d cols but got %d aliases' - % (len(cols), len(header)))) - else: - write_cols = header - else: - write_cols = cols - - if not has_mi_columns: - encoded_labels += list(write_cols) - - else: - - if not has_mi_columns: - encoded_labels += list(cols) + if not has_mi_columns: + encoded_labels += list(write_cols) # write out the mi if has_mi_columns: diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py index 01b42457e72f5..83fd56c676f8e 100644 --- a/pandas/tests/test_frame.py +++ b/pandas/tests/test_frame.py @@ -5836,6 +5836,22 @@ def test_to_csv_no_index(self): result = read_csv(path) assert_frame_equal(df,result) + def test_to_csv_headers(self): + # GH6186, the presence or absence of `index` incorrectly + # causes to_csv to have different header semantics. + pname = '__tmp_to_csv_headers__' + from_df = DataFrame([[1, 2], [3, 4]], columns=['A', 'B']) + to_df = DataFrame([[1, 2], [3, 4]], columns=['X', 'Y']) + with ensure_clean(pname) as path: + from_df.to_csv(path, header=['X', 'Y']) + recons = DataFrame.from_csv(path) + assert_frame_equal(to_df, recons) + + from_df.to_csv(path, index=False, header=['X', 'Y']) + recons = DataFrame.from_csv(path) + recons.reset_index(inplace=True) + assert_frame_equal(to_df, recons) + def test_to_csv_multiindex(self): pname = '__tmp_to_csv_multiindex__'