Skip to content

Commit a1173dc

Browse files
phoflznicholls
authored andcommitted
Regression in to_excel when setting duplicate column names (pandas-dev#39800)
1 parent d819f65 commit a1173dc

File tree

3 files changed

+11
-2
lines changed

3 files changed

+11
-2
lines changed

doc/source/whatsnew/v1.2.3.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 :func:`pandas.to_excel` raising ``KeyError`` when giving duplicate columns with ``columns`` attribute (:issue:`39695`)
1919
-
2020

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

pandas/io/formats/excel.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -475,7 +475,7 @@ def __init__(
475475
if not len(Index(cols).intersection(df.columns)):
476476
raise KeyError("passes columns are not ALL present dataframe")
477477

478-
if len(Index(cols).intersection(df.columns)) != len(cols):
478+
if len(Index(cols).intersection(df.columns)) != len(set(cols)):
479479
# Deprecated in GH#17295, enforced in 1.0.0
480480
raise KeyError("Not all names specified in 'columns' are found")
481481

pandas/tests/io/excel/test_writers.py

+9
Original file line numberDiff line numberDiff line change
@@ -1305,6 +1305,15 @@ def test_raise_when_saving_timezones(self, dtype, tz_aware_fixture, path):
13051305
with pytest.raises(ValueError, match="Excel does not support"):
13061306
df.to_excel(path)
13071307

1308+
def test_excel_duplicate_columns_with_names(self, path):
1309+
# GH#39695
1310+
df = DataFrame({"A": [0, 1], "B": [10, 11]})
1311+
df.to_excel(path, columns=["A", "B", "A"], index=False)
1312+
1313+
result = pd.read_excel(path)
1314+
expected = DataFrame([[0, 10, 0], [1, 11, 1]], columns=["A", "B", "A.1"])
1315+
tm.assert_frame_equal(result, expected)
1316+
13081317

13091318
class TestExcelWriterEngineTests:
13101319
@pytest.mark.parametrize(

0 commit comments

Comments
 (0)