Skip to content
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

ENH: std for dt64 dtype #37436

Merged
merged 6 commits into from
Oct 30, 2020
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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.2.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,7 @@ Other enhancements
- :class:`DataFrame` now supports ``divmod`` operation (:issue:`37165`)
- :meth:`DataFrame.to_parquet` now returns a ``bytes`` object when no ``path`` argument is passed (:issue:`37105`)
- :class:`Rolling` now supports the ``closed`` argument for fixed windows (:issue:`34315`)
- :class:`DatetimeIndex` and :class:`Series` with ``datetime64`` or ``datetime64tz`` dtypes now support ``std`` (:issue:`37436`)

.. _whatsnew_120.api_breaking.python:

Expand Down
22 changes: 22 additions & 0 deletions pandas/core/arrays/datetimes.py
Original file line number Diff line number Diff line change
Expand Up @@ -1856,6 +1856,28 @@ def to_julian_date(self):
/ 24.0
)

# -----------------------------------------------------------------
# Reductions

def std(
self,
axis=None,
dtype=None,
out=None,
ddof: int = 1,
keepdims: bool = False,
skipna: bool = True,
):
# Because std is translation-invariant, we can get self.std
# by calculating (self - Timestamp(0)).std, and we can do it
# without creating a copy by using a view on self._ndarray
from pandas.core.arrays import TimedeltaArray

tda = TimedeltaArray(self._ndarray.view("i8"))
return tda.std(
axis=axis, dtype=dtype, out=out, ddof=ddof, keepdims=keepdims, skipna=skipna
)


# -------------------------------------------------------------------
# Constructor Helpers
Expand Down
2 changes: 2 additions & 0 deletions pandas/core/indexes/datetimes.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ def _new_DatetimeIndex(cls, d):
"date",
"time",
"timetz",
"std",
]
+ DatetimeArray._bool_ops,
DatetimeArray,
Expand Down Expand Up @@ -193,6 +194,7 @@ class DatetimeIndex(DatetimeTimedeltaMixin):
month_name
day_name
mean
std

See Also
--------
Expand Down
4 changes: 3 additions & 1 deletion pandas/core/nanops.py
Original file line number Diff line number Diff line change
Expand Up @@ -755,7 +755,6 @@ def _get_counts_nanvar(
return count, d


@disallow("M8")
@bottleneck_switch(ddof=1)
def nanstd(values, axis=None, skipna=True, ddof=1, mask=None):
"""
Expand Down Expand Up @@ -785,6 +784,9 @@ def nanstd(values, axis=None, skipna=True, ddof=1, mask=None):
>>> nanops.nanstd(s)
1.0
"""
if values.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.

shouldn't this be done in _get_values?

Copy link
Member Author

Choose a reason for hiding this comment

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

this is specific to std

values = values.view("m8[ns]")

orig_dtype = values.dtype
values, mask, _, _, _ = _get_values(values, skipna, mask=mask)

Expand Down
26 changes: 19 additions & 7 deletions pandas/tests/arrays/test_timedeltas.py
Original file line number Diff line number Diff line change
Expand Up @@ -290,8 +290,18 @@ def test_sum_2d_skipna_false(self):
)._values
tm.assert_timedelta_array_equal(result, expected)

def test_std(self):
tdi = pd.TimedeltaIndex(["0H", "4H", "NaT", "4H", "0H", "2H"])
# Adding a Timestamp makes this a test for DatetimeArray.std
Copy link
Contributor

Choose a reason for hiding this comment

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

shouldn't this be in test_datetimes? yes i read your comment, but still the location is odd

@pytest.mark.parametrize(
"add",
[
pd.Timedelta(0),
pd.Timestamp.now(),
pd.Timestamp.now("UTC"),
pd.Timestamp.now("Asia/Tokyo"),
],
)
def test_std(self, add):
tdi = pd.TimedeltaIndex(["0H", "4H", "NaT", "4H", "0H", "2H"]) + add
arr = tdi.array

result = arr.std(skipna=True)
Expand All @@ -303,18 +313,20 @@ def test_std(self):
assert isinstance(result, pd.Timedelta)
assert result == expected

result = nanops.nanstd(np.asarray(arr), skipna=True)
assert isinstance(result, pd.Timedelta)
assert result == expected
if getattr(arr, "tz", None) is None:
result = nanops.nanstd(np.asarray(arr), skipna=True)
assert isinstance(result, pd.Timedelta)
assert result == expected

result = arr.std(skipna=False)
assert result is pd.NaT

result = tdi.std(skipna=False)
assert result is pd.NaT

result = nanops.nanstd(np.asarray(arr), skipna=False)
assert result is pd.NaT
if getattr(arr, "tz", None) is None:
result = nanops.nanstd(np.asarray(arr), skipna=False)
Copy link
Contributor

Choose a reason for hiding this comment

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

are we sure the actual result is correct? e.g. you are just comparing vs the implementation itself. IOW a result which checks a fixed series of datetimes for mean/std would be good.

Copy link
Member Author

Choose a reason for hiding this comment

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

agreed these tests needs fleshing out. im still giving thought to where they should live

Copy link
Contributor

Choose a reason for hiding this comment

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

sure, that's fine about location. i am more concerned with if the results are actually correct; reasoning is that they are converted to i8 but need to make sure that these are coming back correct as well. i am not sure this is actually tested.

Copy link
Member Author

Choose a reason for hiding this comment

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

Yes, we have tests with explicit expected for std() with td64 in test_reductions, test_describe, and test_analytics.

assert result is pd.NaT

def test_median(self):
tdi = pd.TimedeltaIndex(["0H", "3H", "NaT", "5H06m", "0H", "2H"])
Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/reductions/test_stat_reductions.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ def _check_stat_op(
string_series_[5:15] = np.NaN

# mean, idxmax, idxmin, min, and max are valid for dates
if name not in ["max", "min", "mean", "median"]:
if name not in ["max", "min", "mean", "median", "std"]:
ds = Series(pd.date_range("1/1/2001", periods=10))
with pytest.raises(TypeError):
f(ds)
Expand Down