Skip to content

Commit d0c84ce

Browse files
authored
BUG: Fix to_excel writers handling of cols (#31729)
1 parent 31c1856 commit d0c84ce

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
@@ -403,7 +403,7 @@ def __init__(
403403
# Deprecated in GH#17295, enforced in 1.0.0
404404
raise KeyError("Not all names specified in 'columns' are found")
405405

406-
self.df = df
406+
self.df = df.reindex(columns=cols)
407407

408408
self.columns = self.df.columns
409409
self.float_format = float_format

pandas/tests/io/excel/test_writers.py

+21
Original file line numberDiff line numberDiff line change
@@ -1048,6 +1048,27 @@ def test_invalid_columns(self, path):
10481048
):
10491049
write_frame.to_excel(path, "test1", columns=["C", "D"])
10501050

1051+
@pytest.mark.parametrize(
1052+
"to_excel_index,read_excel_index_col",
1053+
[
1054+
(True, 0), # Include index in write to file
1055+
(False, None), # Dont include index in write to file
1056+
],
1057+
)
1058+
def test_write_subset_columns(self, path, to_excel_index, read_excel_index_col):
1059+
# GH 31677
1060+
write_frame = DataFrame({"A": [1, 1, 1], "B": [2, 2, 2], "C": [3, 3, 3]})
1061+
write_frame.to_excel(
1062+
path, "col_subset_bug", columns=["A", "B"], index=to_excel_index
1063+
)
1064+
1065+
expected = write_frame[["A", "B"]]
1066+
read_frame = pd.read_excel(
1067+
path, "col_subset_bug", index_col=read_excel_index_col
1068+
)
1069+
1070+
tm.assert_frame_equal(expected, read_frame)
1071+
10511072
def test_comment_arg(self, path):
10521073
# see gh-18735
10531074
#

0 commit comments

Comments
 (0)