Skip to content

Commit 6ed4cd2

Browse files
Backport PR #31729: BUG: Fix to_excel writers handling of cols (#31764)
1 parent b37b805 commit 6ed4cd2

File tree

3 files changed

+23
-2
lines changed

3 files changed

+23
-2
lines changed

doc/source/whatsnew/v1.0.2.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ including other versions of pandas.
1515
Fixed regressions
1616
~~~~~~~~~~~~~~~~~
1717

18-
-
18+
- Fixed regression in :meth:`DataFrame.to_excel` when ``columns`` kwarg is passed (:issue:`31677`)
1919
-
2020

2121
.. ---------------------------------------------------------------------------

pandas/io/formats/excel.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -400,7 +400,7 @@ def __init__(
400400
# Deprecated in GH#17295, enforced in 1.0.0
401401
raise KeyError("Not all names specified in 'columns' are found")
402402

403-
self.df = df
403+
self.df = df.reindex(columns=cols)
404404

405405
self.columns = self.df.columns
406406
self.float_format = float_format

pandas/tests/io/excel/test_writers.py

+21
Original file line numberDiff line numberDiff line change
@@ -1018,6 +1018,27 @@ def test_invalid_columns(self, path):
10181018
):
10191019
write_frame.to_excel(path, "test1", columns=["C", "D"])
10201020

1021+
@pytest.mark.parametrize(
1022+
"to_excel_index,read_excel_index_col",
1023+
[
1024+
(True, 0), # Include index in write to file
1025+
(False, None), # Dont include index in write to file
1026+
],
1027+
)
1028+
def test_write_subset_columns(self, path, to_excel_index, read_excel_index_col):
1029+
# GH 31677
1030+
write_frame = DataFrame({"A": [1, 1, 1], "B": [2, 2, 2], "C": [3, 3, 3]})
1031+
write_frame.to_excel(
1032+
path, "col_subset_bug", columns=["A", "B"], index=to_excel_index
1033+
)
1034+
1035+
expected = write_frame[["A", "B"]]
1036+
read_frame = pd.read_excel(
1037+
path, "col_subset_bug", index_col=read_excel_index_col
1038+
)
1039+
1040+
tm.assert_frame_equal(expected, read_frame)
1041+
10211042
def test_comment_arg(self, path):
10221043
# see gh-18735
10231044
#

0 commit comments

Comments
 (0)