Skip to content

Commit 41014db

Browse files
Zhengbo WangAloqeely
Zhengbo Wang
andauthored
BUG: Ignore warning for duplicate columns in to_dict when orient='tight' (#58335)
* Ignore warning for duplicate columns in to_dict when orient='tight' * Add whatsnew * Update doc/source/whatsnew/v3.0.0.rst Co-authored-by: Abdulaziz Aloqeely <[email protected]> * Update whatsnew and redefine duplicate columns * Use assert instead * assert not raise and equal --------- Co-authored-by: Abdulaziz Aloqeely <[email protected]>
1 parent ba60432 commit 41014db

File tree

3 files changed

+16
-1
lines changed

3 files changed

+16
-1
lines changed

doc/source/whatsnew/v3.0.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -416,6 +416,7 @@ MultiIndex
416416
I/O
417417
^^^
418418
- Bug in :class:`DataFrame` and :class:`Series` ``repr`` of :py:class:`collections.abc.Mapping`` elements. (:issue:`57915`)
419+
- Bug in :meth:`DataFrame.to_dict` raises unnecessary ``UserWarning`` when columns are not unique and ``orient='tight'``. (:issue:`58281`)
419420
- Bug in :meth:`DataFrame.to_excel` when writing empty :class:`DataFrame` with :class:`MultiIndex` on both axes (:issue:`57696`)
420421
- Bug in :meth:`DataFrame.to_string` that raised ``StopIteration`` with nested DataFrames. (:issue:`16098`)
421422
- Bug in :meth:`read_csv` raising ``TypeError`` when ``index_col`` is specified and ``na_values`` is a dict containing the key ``None``. (:issue:`57547`)

pandas/core/methods/to_dict.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,7 @@ def to_dict(
148148
Return a collections.abc.MutableMapping object representing the
149149
DataFrame. The resulting transformation depends on the `orient` parameter.
150150
"""
151-
if not df.columns.is_unique:
151+
if orient != "tight" and not df.columns.is_unique:
152152
warnings.warn(
153153
"DataFrame columns are not unique, some columns will be omitted.",
154154
UserWarning,

pandas/tests/frame/methods/test_to_dict.py

+14
Original file line numberDiff line numberDiff line change
@@ -513,6 +513,20 @@ def test_to_dict_masked_native_python(self):
513513
result = df.to_dict(orient="records")
514514
assert isinstance(result[0]["a"], int)
515515

516+
def test_to_dict_tight_no_warning_with_duplicate_column(self):
517+
# GH#58281
518+
df = DataFrame([[1, 2], [3, 4], [5, 6]], columns=["A", "A"])
519+
with tm.assert_produces_warning(None):
520+
result = df.to_dict(orient="tight")
521+
expected = {
522+
"index": [0, 1, 2],
523+
"columns": ["A", "A"],
524+
"data": [[1, 2], [3, 4], [5, 6]],
525+
"index_names": [None],
526+
"column_names": [None],
527+
}
528+
assert result == expected
529+
516530

517531
@pytest.mark.parametrize(
518532
"val", [Timestamp(2020, 1, 1), Timedelta(1), Period("2020"), Interval(1, 2)]

0 commit comments

Comments
 (0)