Skip to content
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.1.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -636,6 +636,7 @@ Reshaping
^^^^^^^^^
- Bug in :func:`concat` coercing to ``object`` dtype when one column has ``pa.null()`` dtype (:issue:`53702`)
- Bug in :func:`crosstab` when ``dropna=False`` would not keep ``np.nan`` in the result (:issue:`10772`)
- Bug in :func:`melt` where the ``variable`` column would lose extension dtypes (:issue:`54297`)
- Bug in :func:`merge_asof` raising ``KeyError`` for extension dtypes (:issue:`52904`)
- Bug in :func:`merge_asof` raising ``ValueError`` for data backed by read-only ndarrays (:issue:`53513`)
- Bug in :func:`merge_asof` with ``left_index=True`` or ``right_index=True`` with mismatched index dtypes giving incorrect results in some cases instead of raising ``MergeError`` (:issue:`53870`)
Expand Down
3 changes: 1 addition & 2 deletions pandas/core/reshape/melt.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,8 +141,7 @@ def melt(
else:
mdata[value_name] = frame._values.ravel("F")
for i, col in enumerate(var_name):
# asanyarray will keep the columns as an Index
mdata[col] = np.asanyarray(frame.columns._get_level_values(i)).repeat(N)
Copy link
Member

Choose a reason for hiding this comment

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

excellent! I've got a comment in my "notes to self branch" on this line: # TODO: potential problem with losing EA dtypes?

mdata[col] = frame.columns._get_level_values(i).repeat(N)

result = frame._constructor(mdata, columns=mcolumns)

Expand Down
20 changes: 20 additions & 0 deletions pandas/tests/reshape/test_melt.py
Original file line number Diff line number Diff line change
Expand Up @@ -437,6 +437,26 @@ def test_melt_ea_dtype(self, dtype):
)
tm.assert_frame_equal(result, expected)

def test_melt_ea_columns(self):
# GH 54297
df = DataFrame(
{
"A": {0: "a", 1: "b", 2: "c"},
"B": {0: 1, 1: 3, 2: 5},
"C": {0: 2, 1: 4, 2: 6},
}
)
df.columns = df.columns.astype("string[python]")
result = df.melt(id_vars=["A"], value_vars=["B"])
expected = DataFrame(
{
"A": list("abc"),
"variable": pd.Series(["B"] * 3, dtype="string[python]"),
"value": [1, 3, 5],
}
)
tm.assert_frame_equal(result, expected)


class TestLreshape:
def test_pairs(self):
Expand Down