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 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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.3.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,7 @@ Numeric
Conversion
^^^^^^^^^^
- Bug in :meth:`Series.to_dict` with ``orient='records'`` now returns python native types (:issue:`25969`)
- Bug in :meth:`Series.view` and :meth:`Index.view` when converting between datetime-like (``datetime64[ns]``, ``datetime64[ns, tz]``, ``timedelta64``, ``period``) dtypes (:issue:`39788`)
-
-

Expand Down
28 changes: 27 additions & 1 deletion pandas/core/arrays/datetimelike.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
)
from pandas._libs.tslibs.timestamps import integer_op_not_supported
from pandas._typing import (
ArrayLike,
DatetimeLikeScalar,
Dtype,
DtypeObj,
Expand Down Expand Up @@ -79,6 +80,10 @@
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,
Expand Down Expand Up @@ -428,9 +433,30 @@ 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:
# We handle datetime64, datetime64tz, timedelta64, and period
# dtypes here. Everything else we pass through to the underlying
# ndarray.
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

# we sometimes pass non-dtype objects, e.g np.ndarray;
# pass those through to the underlying 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 @@ -793,6 +793,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: 25 additions & 0 deletions pandas/tests/series/methods/test_view.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import numpy as np
import pytest

from pandas import (
Index,
Series,
array as pd_array,
date_range,
)
import pandas._testing as tm
Expand All @@ -19,3 +24,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)