Skip to content

Commit 1c30d7e

Browse files
REGR: read_sql dropping duplicated columns (#53118)
Co-authored-by: Joris Van den Bossche <[email protected]>
1 parent 69a5073 commit 1c30d7e

File tree

3 files changed

+16
-1
lines changed

3 files changed

+16
-1
lines changed

doc/source/whatsnew/v2.0.2.rst

+1
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ including other versions of pandas.
1313

1414
Fixed regressions
1515
~~~~~~~~~~~~~~~~~
16+
- Fixed regression in :func:`read_sql` dropping columns with duplicated column names (:issue:`53117`)
1617
- Fixed regression in :meth:`DataFrame.loc` losing :class:`MultiIndex` name when enlarging object (:issue:`53053`)
1718
- Fixed regression in :meth:`DataFrame.to_string` printing a backslash at the end of the first row of data, instead of headers, when the DataFrame doesn't fit the line width (:issue:`53054`)
1819
- Fixed regression in :meth:`MultiIndex.join` returning levels in wrong order (:issue:`53093`)

pandas/io/sql.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -161,7 +161,9 @@ def _convert_arrays_to_dataframe(
161161
ArrowExtensionArray(pa.array(arr, from_pandas=True)) for arr in arrays
162162
]
163163
if arrays:
164-
return DataFrame(dict(zip(columns, arrays)))
164+
df = DataFrame(dict(zip(list(range(len(columns))), arrays)))
165+
df.columns = columns
166+
return df
165167
else:
166168
return DataFrame(columns=columns)
167169

pandas/tests/io/test_sql.py

+12
Original file line numberDiff line numberDiff line change
@@ -1492,6 +1492,18 @@ def test_escaped_table_name(self):
14921492

14931493
tm.assert_frame_equal(res, df)
14941494

1495+
def test_read_sql_duplicate_columns(self):
1496+
# GH#53117
1497+
df = DataFrame({"a": [1, 2, 3], "b": [0.1, 0.2, 0.3], "c": 1})
1498+
df.to_sql("test_table", self.conn, index=False)
1499+
1500+
result = pd.read_sql("SELECT a, b, a +1 as a, c FROM test_table;", self.conn)
1501+
expected = DataFrame(
1502+
[[1, 0.1, 2, 1], [2, 0.2, 3, 1], [3, 0.3, 4, 1]],
1503+
columns=["a", "b", "a", "c"],
1504+
)
1505+
tm.assert_frame_equal(result, expected)
1506+
14951507

14961508
@pytest.mark.skipif(not SQLALCHEMY_INSTALLED, reason="SQLAlchemy not installed")
14971509
class TestSQLApi(SQLAlchemyMixIn, _TestSQLApi):

0 commit comments

Comments
 (0)