Skip to content

Commit ec92c33

Browse files
Backport PR #39800: Regression in to_excel when setting duplicate column names (#39827)
Co-authored-by: patrick <[email protected]>
1 parent e96bb37 commit ec92c33

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
@@ -465,7 +465,7 @@ def __init__(
465465
if not len(Index(cols).intersection(df.columns)):
466466
raise KeyError("passes columns are not ALL present dataframe")
467467

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

pandas/tests/io/excel/test_writers.py

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

1298+
def test_excel_duplicate_columns_with_names(self, path):
1299+
# GH#39695
1300+
df = DataFrame({"A": [0, 1], "B": [10, 11]})
1301+
df.to_excel(path, columns=["A", "B", "A"], index=False)
1302+
1303+
result = pd.read_excel(path)
1304+
expected = DataFrame([[0, 10, 0], [1, 11, 1]], columns=["A", "B", "A.1"])
1305+
tm.assert_frame_equal(result, expected)
1306+
12981307

12991308
class TestExcelWriterEngineTests:
13001309
@pytest.mark.parametrize(

0 commit comments

Comments
 (0)