Skip to content

ENH: preserve non-nano DTA/TDA in Index/Series/DataFrame #47230

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 7 commits into from
Jun 15, 2022
Merged
Show file tree
Hide file tree
Changes from 2 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
12 changes: 12 additions & 0 deletions pandas/core/indexes/datetimes.py
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,18 @@ def __new__(

name = maybe_extract_name(name, data, cls)

if (
isinstance(data, DatetimeArray)
and freq is lib.no_default
and tz is None
and dtype is None
):
# fastpath, similar logic in TimedeltaIndex.__new__;
# Note in this particular case we retain non-nano.
if copy:
data = data.copy()
return cls._simple_new(data, name=name)

dtarr = DatetimeArray._from_sequence_not_strict(
data,
dtype=dtype,
Expand Down
1 change: 1 addition & 0 deletions pandas/core/indexes/timedeltas.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,7 @@ def __new__(
"represent unambiguous timedelta values durations."
)

# FIXME: need to check for dtype/data match
if isinstance(data, TimedeltaArray) and freq is lib.no_default:
if copy:
data = data.copy()
Expand Down
11 changes: 6 additions & 5 deletions pandas/core/internals/construction.py
Original file line number Diff line number Diff line change
Expand Up @@ -537,15 +537,16 @@ def treat_as_nested(data) -> bool:
# ---------------------------------------------------------------------


def _prep_ndarray(values, copy: bool = True) -> np.ndarray:
def _prep_ndarray(
Copy link
Contributor

Choose a reason for hiding this comment

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

maybe rename to prep_array_like or similar?

values, copy: bool = True
) -> np.ndarray | DatetimeArray | TimedeltaArray:
if isinstance(values, TimedeltaArray) or (
isinstance(values, DatetimeArray) and values.tz is None
):
# On older numpy, np.asarray below apparently does not call __array__,
# so nanoseconds get dropped.
values = values._ndarray
# By retaining DTA/TDA instead of unpacking, we end up retaining non-nano
pass

if not isinstance(values, (np.ndarray, ABCSeries, Index)):
elif not isinstance(values, (np.ndarray, ABCSeries, Index)):
if len(values) == 0:
return np.empty((0, 0), dtype=object)
elif isinstance(values, range):
Expand Down
53 changes: 52 additions & 1 deletion pandas/tests/frame/test_constructors.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,10 @@
import pytest
import pytz

from pandas.compat import np_version_under1p19
from pandas.compat import (
is_platform_mac,
np_version_under1p19,
)
import pandas.util._test_decorators as td

from pandas.core.dtypes.common import is_integer_dtype
Expand Down Expand Up @@ -53,6 +56,7 @@
IntervalArray,
PeriodArray,
SparseArray,
TimedeltaArray,
)
from pandas.core.api import Int64Index

Expand Down Expand Up @@ -3086,3 +3090,50 @@ def test_tzaware_data_tznaive_dtype(self, constructor):

assert np.all(result.dtypes == "M8[ns]")
assert np.all(result == ts_naive)


# TODO: better location for this test?
class TestAllowNonNano:
# Until 2.0, we do not preserve non-nano dt64/td64 when passed as ndarray,
# but do preserve it when passed as DTA/TDA

@pytest.fixture(params=[True, False])
def as_td(self, request):
return request.param

@pytest.fixture
def arr(self, as_td):
values = np.arange(5).astype(np.int64).view("M8[s]")
if as_td:
values = values - values[0]
return TimedeltaArray._simple_new(values, dtype=values.dtype)
else:
return DatetimeArray._simple_new(values, dtype=values.dtype)

def test_index_allow_non_nano(self, arr):
idx = Index(arr)
assert idx.dtype == arr.dtype

def test_dti_tdi_allow_non_nano(self, arr, as_td):
if as_td:
idx = pd.TimedeltaIndex(arr)
else:
idx = DatetimeIndex(arr)
assert idx.dtype == arr.dtype

def test_series_allow_non_nano(self, arr):
ser = Series(arr)
assert ser.dtype == arr.dtype

def test_frame_allow_non_nano(self, arr):
df = DataFrame(arr)
assert df.dtypes[0] == arr.dtype

@pytest.mark.xfail(
is_platform_mac(),
reason="stack_arrays converts TDA to ndarray, then goes "
"through ensure_wrapped_if_datetimelike",
)
def test_frame_from_dict_allow_non_nano(self, arr):
df = DataFrame({0: arr})
assert df.dtypes[0] == arr.dtype