Skip to content

Commit 2344d65

Browse files
committed
This fix enables you to preserve the datetime precision when using the melt method. It fixes the issues raised in #55254.
1 parent d01669f commit 2344d65

File tree

2 files changed

+48
-2
lines changed

2 files changed

+48
-2
lines changed

pandas/core/reshape/melt.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,10 @@
77

88
from pandas.util._decorators import Appender
99

10-
from pandas.core.dtypes.common import is_list_like
10+
from pandas.core.dtypes.common import (
11+
DatetimeTZDtype,
12+
is_list_like,
13+
)
1114
from pandas.core.dtypes.concat import concat_compat
1215
from pandas.core.dtypes.missing import notna
1316

@@ -134,7 +137,9 @@ def melt(
134137

135138
mcolumns = id_vars + var_name + [value_name]
136139

137-
if frame.shape[1] > 0:
140+
if frame.shape[1] > 0 and not any(
141+
isinstance(dt, DatetimeTZDtype) for dt in frame.dtypes.values
142+
):
138143
mdata[value_name] = concat(
139144
[frame.iloc[:, i] for i in range(frame.shape[1])]
140145
).values

pandas/tests/reshape/test_melt.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -459,6 +459,47 @@ def test_melt_ea_columns(self):
459459
)
460460
tm.assert_frame_equal(result, expected)
461461

462+
def test_melt_preserves_datetime(self):
463+
df = DataFrame(
464+
data=[
465+
{
466+
"type": "A0",
467+
"start_date": pd.Timestamp("2023/03/01", tz="Asia/Tokyo"),
468+
"end_date": pd.Timestamp("2023/03/10", tz="Asia/Tokyo"),
469+
},
470+
{
471+
"type": "A1",
472+
"start_date": pd.Timestamp("2023/03/01", tz="Asia/Tokyo"),
473+
"end_date": pd.Timestamp("2023/03/11", tz="Asia/Tokyo"),
474+
},
475+
],
476+
index=["aaaa", "bbbb"],
477+
)
478+
result = df.melt(
479+
id_vars=["type"],
480+
value_vars=["start_date", "end_date"],
481+
var_name="start/end",
482+
value_name="date",
483+
)
484+
expected = DataFrame(
485+
{
486+
"type": {0: "A0", 1: "A1", 2: "A0", 3: "A1"},
487+
"start/end": {
488+
0: "start_date",
489+
1: "start_date",
490+
2: "end_date",
491+
3: "end_date",
492+
},
493+
"date": {
494+
0: pd.Timestamp("2023-03-01 00:00:00+0900", tz="Asia/Tokyo"),
495+
1: pd.Timestamp("2023-03-01 00:00:00+0900", tz="Asia/Tokyo"),
496+
2: pd.Timestamp("2023-03-10 00:00:00+0900", tz="Asia/Tokyo"),
497+
3: pd.Timestamp("2023-03-11 00:00:00+0900", tz="Asia/Tokyo"),
498+
},
499+
}
500+
)
501+
tm.assert_frame_equal(result, expected)
502+
462503

463504
class TestLreshape:
464505
def test_pairs(self):

0 commit comments

Comments
 (0)