Skip to content

REGR: read_sql dropping duplicated columns #53118

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 8, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/source/whatsnew/v2.0.2.rst
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ including other versions of pandas.

Fixed regressions
~~~~~~~~~~~~~~~~~
- Fixed regression in :func:`read_sql` dropping columns with duplicated column names (:issue:`53117`)
- Fixed regression in :meth:`DataFrame.loc` losing :class:`MultiIndex` name when enlarging object (:issue:`53053`)
- 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`)
- Fixed regression in :meth:`MultiIndex.join` returning levels in wrong order (:issue:`53093`)
Expand Down
4 changes: 3 additions & 1 deletion pandas/io/sql.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,9 @@ def _convert_arrays_to_dataframe(
ArrowExtensionArray(pa.array(arr, from_pandas=True)) for arr in arrays
]
if arrays:
return DataFrame(dict(zip(columns, arrays)))
df = DataFrame(dict(zip(list(range(len(columns))), arrays)))
df.columns = columns
return df
else:
return DataFrame(columns=columns)

Expand Down
12 changes: 12 additions & 0 deletions pandas/tests/io/test_sql.py
Original file line number Diff line number Diff line change
Expand Up @@ -1492,6 +1492,18 @@ def test_escaped_table_name(self):

tm.assert_frame_equal(res, df)

def test_read_sql_duplicate_columns(self):
# GH#53117
df = DataFrame({"a": [1, 2, 3], "b": [0.1, 0.2, 0.3], "c": 1})
df.to_sql("test_table", self.conn, index=False)

result = pd.read_sql("SELECT a, b, a +1 as a, c FROM test_table;", self.conn)
expected = DataFrame(
[[1, 0.1, 2, 1], [2, 0.2, 3, 1], [3, 0.3, 4, 1]],
columns=["a", "b", "a", "c"],
)
tm.assert_frame_equal(result, expected)


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