Skip to content

BUG: Let melt name multiple variable columns for labels from a MultiIndex #58088

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 4 commits into from
May 25, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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.2.2.rst
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ Fixed regressions
~~~~~~~~~~~~~~~~~
- :meth:`DataFrame.__dataframe__` was producing incorrect data buffers when the a column's type was a pandas nullable on with missing values (:issue:`56702`)
- :meth:`DataFrame.__dataframe__` was producing incorrect data buffers when the a column's type was a pyarrow nullable on with missing values (:issue:`57664`)
- :meth:`DataFrame.melt` would not accept multiple names in ``var_name`` when the columns were a :class:`MultiIndex` (:issue:`58033`)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you move this to v3.0.0rst?

- Avoid issuing a spurious ``DeprecationWarning`` when a custom :class:`DataFrame` or :class:`Series` subclass method is called (:issue:`57553`)
- Fixed regression in precision of :func:`to_datetime` with string and ``unit`` input (:issue:`57051`)

Expand Down
15 changes: 12 additions & 3 deletions pandas/core/reshape/melt.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,10 @@ def melt(
value_vars : scalar, tuple, list, or ndarray, optional
Column(s) to unpivot. If not specified, uses all columns that
are not set as `id_vars`.
var_name : scalar, default None
var_name : scalar, tuple, list, or ndarray, optional
Name to use for the 'variable' column. If None it uses
``frame.columns.name`` or 'variable'.
``frame.columns.name`` or 'variable'. Must be a scalar if columns are a
MultiIndex.
value_name : scalar, default 'value'
Name to use for the 'value' column, can't be an existing column label.
col_level : scalar, optional
Expand Down Expand Up @@ -217,7 +218,15 @@ def melt(
frame.columns.name if frame.columns.name is not None else "variable"
]
elif is_list_like(var_name):
raise ValueError(f"{var_name=} must be a scalar.")
if isinstance(frame.columns, MultiIndex):
var_name = list(var_name)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is the list cast needed here? it should be Sized to compute len

Copy link
Contributor Author

@rob-sil rob-sil May 21, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

var_name will be iterated on twice, so I think there's a pathological case where you could have a single-use object that has __len__ and __iter__.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah true. Could you use is_iterator to check for the single use object and cast to list if so?

if len(var_name) > len(frame.columns):
raise ValueError(
f"{var_name=} has {len(var_name)} items, "
f"but the dataframe columns only have {len(frame.columns)} levels."
)
else:
raise ValueError(f"{var_name=} must be a scalar.")
else:
var_name = [var_name]

Expand Down
16 changes: 16 additions & 0 deletions pandas/tests/reshape/test_melt.py
Original file line number Diff line number Diff line change
Expand Up @@ -533,6 +533,22 @@ def test_melt_non_scalar_var_name_raises(self):
with pytest.raises(ValueError, match=r".* must be a scalar."):
df.melt(id_vars=["a"], var_name=[1, 2])

def test_melt_multiindex_columns_var_name(self):
# GH 58033
df = DataFrame({("A", "a"): [1], ("A", "b"): [2]})

expected = DataFrame(
[("A", "a", 1), ("A", "b", 2)], columns=["first", "second", "value"]
)

tm.assert_frame_equal(df.melt(var_name=["first", "second"]), expected)
tm.assert_frame_equal(df.melt(var_name=["first"]), expected[["first", "value"]])

with pytest.raises(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you make this a separate test?

ValueError, match="but the dataframe columns only have 2 levels"
):
df.melt(var_name=["first", "second", "third"])


class TestLreshape:
def test_pairs(self):
Expand Down
Loading