Skip to content

Commit 997c914

Browse files
authored
BUG: DataFrame.melt gives unexpected result when column "value" already exists (pandas-dev#35003)
1 parent 1d6f2bf commit 997c914

File tree

3 files changed

+26
-0
lines changed

3 files changed

+26
-0
lines changed

doc/source/whatsnew/v1.1.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -819,6 +819,7 @@ Deprecations
819819
- :meth:`util.testing.assert_almost_equal` now accepts both relative and absolute
820820
precision through the ``rtol``, and ``atol`` parameters, thus deprecating the
821821
``check_less_precise`` parameter. (:issue:`13357`).
822+
- :func:`DataFrame.melt` accepting a value_name that already exists is deprecated, and will be removed in a future version (:issue:`34731`)
822823

823824
.. ---------------------------------------------------------------------------
824825

pandas/core/reshape/melt.py

+11
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import re
22
from typing import TYPE_CHECKING, List, cast
3+
import warnings
34

45
import numpy as np
56

@@ -40,6 +41,16 @@ def melt(
4041
else:
4142
cols = list(frame.columns)
4243

44+
if value_name in frame.columns:
45+
warnings.warn(
46+
"This dataframe has a column name that matches the 'value_name' column "
47+
"name of the resultiing Dataframe. "
48+
"In the future this will raise an error, please set the 'value_name' "
49+
"parameter of DataFrame.melt to a unique name.",
50+
FutureWarning,
51+
stacklevel=3,
52+
)
53+
4354
if id_vars is not None:
4455
if not is_list_like(id_vars):
4556
id_vars = [id_vars]

pandas/tests/reshape/test_melt.py

+14
Original file line numberDiff line numberDiff line change
@@ -1014,3 +1014,17 @@ def test_col_substring_of_stubname(self):
10141014
)
10151015
result = pd.wide_to_long(wide_df, stubnames="PA", i=["node_id", "A"], j="time")
10161016
tm.assert_frame_equal(result, expected)
1017+
1018+
def test_warn_of_column_name_value(self):
1019+
# GH34731
1020+
# raise a warning if the resultant value column name matches
1021+
# a name in the dataframe already (default name is "value")
1022+
df = pd.DataFrame({"col": list("ABC"), "value": range(10, 16, 2)})
1023+
expected = pd.DataFrame(
1024+
[["A", "col", "A"], ["B", "col", "B"], ["C", "col", "C"]],
1025+
columns=["value", "variable", "value"],
1026+
)
1027+
1028+
with tm.assert_produces_warning(FutureWarning):
1029+
result = df.melt(id_vars="value")
1030+
tm.assert_frame_equal(result, expected)

0 commit comments

Comments
 (0)