Skip to content

ENH: Return DatetimeIndex or TimedeltaIndex bins for q/cut when input is datelike #20956

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 15 commits into from
Jul 3, 2018
Merged
Show file tree
Hide file tree
Changes from 8 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/v0.23.0.txt
Original file line number Diff line number Diff line change
Expand Up @@ -550,6 +550,7 @@ Other Enhancements
- :func:`to_hdf` and :func:`read_hdf` now accept an ``errors`` keyword argument to control encoding error handling (:issue:`20835`)
- :func:`cut` has gained the ``duplicates='raise'|'drop'`` option to control whether to raise on duplicated edges (:issue:`20947`)
- :func:`date_range`, :func:`timedelta_range`, and :func:`interval_range` now return a linearly spaced index if ``start``, ``stop``, and ``periods`` are specified, but ``freq`` is not. (:issue:`20808`, :issue:`20983`, :issue:`20976`)
- :func:`cut` and :func:`qcut` now returns a :class:`DatetimeIndex` or :class:`TimedeltaIndex` bins when the input is datetime or timedelta dtype respectively and ``retbins=True`` (:issue:`19891`)
Copy link
Contributor

Choose a reason for hiding this comment

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

move to 0.24


.. _whatsnew_0230.api_breaking:

Expand Down
27 changes: 26 additions & 1 deletion pandas/core/reshape/tile.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
from pandas._libs.lib import infer_dtype
from pandas import (to_timedelta, to_datetime,
Categorical, Timestamp, Timedelta,
Series, Interval, IntervalIndex)
Series, Index, Interval, IntervalIndex)

import numpy as np

Expand Down Expand Up @@ -364,6 +364,8 @@ def _bins_to_cuts(x, bins, right=True, labels=None,
result = result.astype(np.float64)
np.putmask(result, na_mask, np.nan)

bins = _convert_bin_to_datelike_type(bins, dtype)
Copy link
Contributor

Choose a reason for hiding this comment

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

instead of this just call Index() which will do all of this inference

Copy link
Contributor

Choose a reason for hiding this comment

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

is there a way to make this logic flow better, e.g. _convert_bins_to_numeric_type and _convert_bin_to_datelike_type are disjointed (e.g. they are separate), maybe combine? I just find that we are doing conversions in 2 places here

Copy link
Member Author

Choose a reason for hiding this comment

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

Well they both serve different purposes;
_convert_bins_to_numeric_type is used at the start to prep the bins (datelike data -> numeric data) before the main array is cut.

_convert_bin_to_datelike_type is used at the end to "stylize" the bins (numeric data -> datelike data) after the array is cut.

Plus, I like the explicit naming of these two processes. Just my 2c.

Copy link
Contributor

Choose a reason for hiding this comment

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

ok that's fine then.


return result, bins


Expand Down Expand Up @@ -428,6 +430,29 @@ def _convert_bin_to_numeric_type(bins, dtype):
return bins


def _convert_bin_to_datelike_type(bins, dtype):
"""
Convert bins to a DatetimeIndex or TimedeltaIndex if the orginal dtype is
datelike

Parameters
----------
bins : list-like of bins
dtype : dtype of data

Returns
-------
bins : Array-like of bins, DatetimeIndex or TimedeltaIndex if dtype is
datelike
"""
# Can be simplified once GH 20964 is fixed.
Copy link
Contributor

Choose a reason for hiding this comment

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

would like to fix #20964 first

if is_datetime64tz_dtype(dtype):
bins = to_datetime(bins, utc=True).tz_convert(dtype.tz)
elif is_datetime64_dtype(dtype) or is_timedelta64_dtype(dtype):
bins = Index(bins, dtype=dtype)
return bins


def _format_labels(bins, precision, right=True,
include_lowest=False, dtype=None):
""" based on the dtype, return our labels """
Expand Down
38 changes: 37 additions & 1 deletion pandas/tests/reshape/test_tile.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
import pandas as pd
from pandas import (DataFrame, Series, isna, to_datetime, DatetimeIndex, Index,
Timestamp, Interval, IntervalIndex, Categorical,
cut, qcut, date_range, NaT, TimedeltaIndex)
cut, qcut, date_range, timedelta_range, NaT,
TimedeltaIndex)
from pandas.tseries.offsets import Nano, Day
import pandas.util.testing as tm
from pandas.api.types import CategoricalDtype as CDT
Expand Down Expand Up @@ -605,3 +606,38 @@ def f():
mask = result.isna()
tm.assert_numpy_array_equal(
mask, np.array([False, True, True, True, True]))

@pytest.mark.parametrize('tz', [None, 'UTC', 'US/Pacific'])
def test_datetime_cut_roundtrip(self, tz):
# GH 19891
s = Series(date_range('20180101', periods=3, tz=tz))
result, result_bins = cut(s, 2, retbins=True)
expected = cut(s, result_bins)
tm.assert_series_equal(result, expected)
expected_bins = DatetimeIndex(['2017-12-31 23:57:07.200000',
'2018-01-02 00:00:00',
'2018-01-03 00:00:00'])
expected_bins = expected_bins.tz_localize(tz)
tm.assert_index_equal(result_bins, expected_bins)

def test_timedelta_cut_roundtrip(self):
# GH 19891
s = Series(timedelta_range('1day', periods=3))
result, result_bins = cut(s, 2, retbins=True)
expected = cut(s, result_bins)
tm.assert_series_equal(result, expected)
expected_bins = TimedeltaIndex(['0 days 23:57:07.200000',
'2 days 00:00:00',
'3 days 00:00:00'])
tm.assert_index_equal(result_bins, expected_bins)

@pytest.mark.parametrize('arg, expected_bins', [
[timedelta_range('1day', periods=3),
TimedeltaIndex(['1 days', '2 days', '3 days'])],
[date_range('20180101', periods=3),
DatetimeIndex(['2018-01-01', '2018-01-02', '2018-01-03'])]])
def test_datelike_qcut_bins(self, arg, expected_bins):
# GH 19891
s = Series(arg)
result, result_bins = qcut(s, 2, retbins=True)
tm.assert_index_equal(result_bins, expected_bins)