Skip to content

Commit 309f9ef

Browse files
authored
BUG: melt with extension dtype column (#54297)
* BUG: melt with extension dtype column * add whatsnew num
1 parent 069554a commit 309f9ef

File tree

3 files changed

+22
-2
lines changed

3 files changed

+22
-2
lines changed

doc/source/whatsnew/v2.1.0.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -640,6 +640,7 @@ Reshaping
640640
^^^^^^^^^
641641
- Bug in :func:`concat` coercing to ``object`` dtype when one column has ``pa.null()`` dtype (:issue:`53702`)
642642
- Bug in :func:`crosstab` when ``dropna=False`` would not keep ``np.nan`` in the result (:issue:`10772`)
643+
- Bug in :func:`melt` where the ``variable`` column would lose extension dtypes (:issue:`54297`)
643644
- Bug in :func:`merge_asof` raising ``KeyError`` for extension dtypes (:issue:`52904`)
644645
- Bug in :func:`merge_asof` raising ``ValueError`` for data backed by read-only ndarrays (:issue:`53513`)
645646
- 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`)

pandas/core/reshape/melt.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -141,8 +141,7 @@ def melt(
141141
else:
142142
mdata[value_name] = frame._values.ravel("F")
143143
for i, col in enumerate(var_name):
144-
# asanyarray will keep the columns as an Index
145-
mdata[col] = np.asanyarray(frame.columns._get_level_values(i)).repeat(N)
144+
mdata[col] = frame.columns._get_level_values(i).repeat(N)
146145

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

pandas/tests/reshape/test_melt.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -437,6 +437,26 @@ def test_melt_ea_dtype(self, dtype):
437437
)
438438
tm.assert_frame_equal(result, expected)
439439

440+
def test_melt_ea_columns(self):
441+
# GH 54297
442+
df = DataFrame(
443+
{
444+
"A": {0: "a", 1: "b", 2: "c"},
445+
"B": {0: 1, 1: 3, 2: 5},
446+
"C": {0: 2, 1: 4, 2: 6},
447+
}
448+
)
449+
df.columns = df.columns.astype("string[python]")
450+
result = df.melt(id_vars=["A"], value_vars=["B"])
451+
expected = DataFrame(
452+
{
453+
"A": list("abc"),
454+
"variable": pd.Series(["B"] * 3, dtype="string[python]"),
455+
"value": [1, 3, 5],
456+
}
457+
)
458+
tm.assert_frame_equal(result, expected)
459+
440460

441461
class TestLreshape:
442462
def test_pairs(self):

0 commit comments

Comments
 (0)