Skip to content

BUG: DTA/TDA/PA/Series/Index.view with datetimelike #39788

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 8 commits into from
Feb 21, 2021
Merged
Show file tree
Hide file tree
Changes from 3 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
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v1.3.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -312,7 +312,7 @@ Numeric

Conversion
^^^^^^^^^^
-
- Bug in :meth:`Series.view` and :meth:`Index.view` when converting between datetime-like (``datetime64[ns]``, ``datetime64[ns, tz]``, ``timedelta64``, ``period``) dtypes (:issue:`39788`)
-

Strings
Expand Down
22 changes: 20 additions & 2 deletions pandas/core/arrays/datetimelike.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
)
from pandas._libs.tslibs.fields import RoundTo, round_nsint64
from pandas._libs.tslibs.timestamps import integer_op_not_supported
from pandas._typing import DatetimeLikeScalar, Dtype, DtypeObj, NpDtype
from pandas._typing import ArrayLike, DatetimeLikeScalar, Dtype, DtypeObj, NpDtype
from pandas.compat.numpy import function as nv
from pandas.errors import AbstractMethodError, NullFrequencyError, PerformanceWarning
from pandas.util._decorators import Appender, Substitution, cache_readonly
Expand All @@ -57,6 +57,7 @@
is_unsigned_integer_dtype,
pandas_dtype,
)
from pandas.core.dtypes.dtypes import DatetimeTZDtype, PeriodDtype
from pandas.core.dtypes.missing import is_valid_na_for_dtype, isna

from pandas.core import nanops, ops
Expand Down Expand Up @@ -381,9 +382,26 @@ def astype(self, dtype, copy=True):
else:
return np.asarray(self, dtype=dtype)

def view(self, dtype: Optional[Dtype] = None):
def view(self, dtype: Optional[Dtype] = None) -> ArrayLike:
if dtype is None or dtype is self.dtype:
return type(self)(self._ndarray, dtype=self.dtype)

if isinstance(dtype, type):
Copy link
Contributor

Choose a reason for hiding this comment

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

i think make this clear that M8[ns] (or really M8[s]) or whatever will hit here, but a tz-aware / pandas dtype will pass thru. yes after i read it i get it, but in 3 months no-one will remember.

Copy link
Member Author

Choose a reason for hiding this comment

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

fleshing out the comment bc its pretty weird. this line isnt catching np.dtype, its catching type, e.g. we get here with dtype=np.ndarray

Copy link
Member Author

Choose a reason for hiding this comment

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

updated + green

# e.g. np.ndarray
return self._ndarray.view(dtype)

dtype = pandas_dtype(dtype)
if isinstance(dtype, (PeriodDtype, DatetimeTZDtype)):
cls = dtype.construct_array_type()
return cls._simple_new(self.asi8, dtype=dtype)
elif dtype == "M8[ns]":
from pandas.core.arrays import DatetimeArray

return DatetimeArray._simple_new(self.asi8, dtype=dtype)
elif dtype == "m8[ns]":
from pandas.core.arrays import TimedeltaArray

return TimedeltaArray._simple_new(self.asi8.view("m8[ns]"), dtype=dtype)
return self._ndarray.view(dtype=dtype)

# ------------------------------------------------------------------
Expand Down
17 changes: 17 additions & 0 deletions pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -747,6 +747,23 @@ def view(self, cls=None):
# we need to see if we are subclassing an
# index type here
if cls is not None and not hasattr(cls, "_typ"):
dtype = cls
if isinstance(cls, str):
dtype = pandas_dtype(cls)

if isinstance(dtype, (np.dtype, ExtensionDtype)) and needs_i8_conversion(
dtype
):
if dtype.kind == "m" and dtype != "m8[ns]":
Copy link
Contributor

Choose a reason for hiding this comment

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

you can handle all m and M types via this branch?

Copy link
Member Author

Choose a reason for hiding this comment

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

L757-L759 is for non-nano td64. L754-L765 handles all td64, dt64, dt64tz, and perioddtype

Copy link
Contributor

Choose a reason for hiding this comment

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

i think this could use a little more commentary here (similar to what you did on the datetimelike astype), pls catch in a followon

# e.g. m8[s]
return self._data.view(cls)

arr = self._data.view("i8")
idx_cls = self._dtype_to_subclass(dtype)
arr_cls = idx_cls._data_cls
arr = arr_cls._simple_new(self._data.view("i8"), dtype=dtype)
return idx_cls._simple_new(arr, name=self.name)

result = self._data.view(cls)
else:
result = self._view()
Expand Down
25 changes: 24 additions & 1 deletion pandas/tests/series/methods/test_view.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
from pandas import Series, date_range
import numpy as np
import pytest

from pandas import Index, Series, array as pd_array, date_range
import pandas._testing as tm


Expand All @@ -16,3 +19,23 @@ def test_view_tz(self):
]
)
tm.assert_series_equal(result, expected)

@pytest.mark.parametrize(
"first", ["m8[ns]", "M8[ns]", "M8[ns, US/Central]", "period[D]"]
)
@pytest.mark.parametrize(
"second", ["m8[ns]", "M8[ns]", "M8[ns, US/Central]", "period[D]"]
)
@pytest.mark.parametrize("box", [Series, Index, pd_array])
def test_view_between_datetimelike(self, first, second, box):

dti = date_range("2016-01-01", periods=3)

orig = box(dti)
obj = orig.view(first)
assert obj.dtype == first
tm.assert_numpy_array_equal(np.asarray(obj.view("i8")), dti.asi8)

res = obj.view(second)
assert res.dtype == second
tm.assert_numpy_array_equal(np.asarray(obj.view("i8")), dti.asi8)