diff --git a/pandas/core/frame.py b/pandas/core/frame.py index b5462bbe67647f..9920ddf8548505 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -972,7 +972,8 @@ def to_dict(self, orient='dict', into=dict): """ if not self.columns.is_unique: warnings.warn("DataFrame columns are not unique, some " - "columns will be omitted.", UserWarning) + "columns will be omitted.", UserWarning, + stacklevel=2) # GH16122 into_c = standardize_mapping(into) if orient.lower().startswith('d'): diff --git a/pandas/tests/frame/test_convert_to.py b/pandas/tests/frame/test_convert_to.py index 34dd138ee1c807..629c695b702fe2 100644 --- a/pandas/tests/frame/test_convert_to.py +++ b/pandas/tests/frame/test_convert_to.py @@ -216,6 +216,13 @@ def test_to_dict_errors(self, mapping): with pytest.raises(TypeError): df.to_dict(into=mapping) + def test_to_dict_not_unique_warning(self): + # GH16927: When converting to a dict, if a column has a non-unique name + # it will be dropped, throwing a warning. + df = DataFrame([[1, 2, 3]], columns=['a', 'a', 'b']) + with tm.assert_produces_warning(UserWarning): + df.to_dict() + @pytest.mark.parametrize('tz', ['UTC', 'GMT', 'US/Eastern']) def test_to_records_datetimeindex_with_tz(self, tz): # GH13937