Skip to content

Fix explode to preserve datetime unit in Series and DataFrame; update… #61612

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

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
14 changes: 13 additions & 1 deletion pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@
notna,
)

import pandas as pd
from pandas.core import (
algorithms,
common as com,
Expand Down Expand Up @@ -9903,13 +9904,24 @@ def explode(
df = self.reset_index(drop=True)
if len(columns) == 1:
result = df[columns[0]].explode()
orig_dtype = df[columns[0]].dtype
if pd.api.types.is_datetime64_dtype(orig_dtype):
result = result.astype(orig_dtype)
Comment on lines +9907 to +9909
Copy link
Member

Choose a reason for hiding this comment

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

This is just working around the issue. .explode should have preserved the datetime unit

else:
mylen = lambda x: len(x) if (is_list_like(x) and len(x) > 0) else 1
counts0 = self[columns[0]].apply(mylen)
for c in columns[1:]:
if not all(counts0 == self[c].apply(mylen)):
raise ValueError("columns must have matching element counts")
result = DataFrame({c: df[c].explode() for c in columns})
result_data = {}
for c in columns:
exploded_series = df[c].explode()
orig_dtype = df[c].dtype
if pd.api.types.is_datetime64_dtype(orig_dtype):
exploded_series = exploded_series.astype(orig_dtype)
result_data[c] = exploded_series
result = DataFrame(result_data)

result = df.drop(columns, axis=1).join(result)
if ignore_index:
result.index = default_index(len(result))
Expand Down
38 changes: 38 additions & 0 deletions pandas/tests/series/methods/test_explode.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,3 +175,41 @@ def test_explode_pyarrow_non_list_type(ignore_index):
result = ser.explode(ignore_index=ignore_index)
expected = pd.Series([1, 2, 3], dtype="int64[pyarrow]", index=[0, 1, 2])
tm.assert_series_equal(result, expected)


def test_explode_preserves_datetime_unit():
# Create datetime64[ms] array manually
dt64_ms = np.array(
[
"2020-01-01T00:00:00.000",
"2020-01-01T01:00:00.000",
"2020-01-01T02:00:00.000",
],
dtype="datetime64[ms]",
)
s = pd.Series([dt64_ms])

# Explode the Series
result = s.explode()

# Ensure the dtype (including unit) is preserved
assert result.dtype == dt64_ms.dtype, (
f"Expected dtype {dt64_ms.dtype}, got {result.dtype}"
)


def test_single_column_explode_preserves_datetime_unit():
# Use freq in ms since unit='ms'
rng = pd.date_range("2020-01-01T00:00:00Z", periods=3, freq="3600000ms", unit="ms")
s = pd.Series([rng])
result = s.explode()
assert result.dtype == rng.dtype


def test_multi_column_explode_preserves_datetime_unit():
rng1 = pd.date_range("2020-01-01", periods=2, freq="3600000ms", unit="ms")
rng2 = pd.date_range("2020-01-01", periods=2, freq="3600000ms", unit="ms")
df = pd.DataFrame({"A": [rng1], "B": [rng2]})
result = df.explode(["A", "B"])
assert result["A"].dtype == rng1.dtype
assert result["B"].dtype == rng2.dtype
Loading