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 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
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 @@ -524,6 +524,7 @@ Other Enhancements
- Added new writer for exporting Stata dta files in version 117, ``StataWriter117``. This format supports exporting strings with lengths up to 2,000,000 characters (:issue:`16450`)
- :func:`to_hdf` and :func:`read_hdf` now accept an ``errors`` keyword argument to control encoding error handling (:issue:`20835`)
- :func:`date_range` now returns a linearly spaced ``DatetimeIndex`` if ``start``, ``stop``, and ``periods`` are specified, but ``freq`` is not. (:issue:`20808`)
- :func:`cut` and :func:`qcut` now returns a ``DatetimeIndex`` or ``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.

can you add :class: for DTI / TDI


.. _whatsnew_0230.api_breaking:

Expand Down
26 changes: 26 additions & 0 deletions pandas/core/reshape/tile.py
Original file line number Diff line number Diff line change
Expand Up @@ -332,6 +332,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 @@ -396,6 +398,30 @@ 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
"""
if is_datetime64tz_dtype(dtype):
bins = to_datetime(bins, utc=True).tz_convert(dtype.tz)
elif is_datetime64_dtype(dtype):
bins = to_datetime(bins)
elif is_timedelta64_dtype(dtype):
bins = to_timedelta(bins)
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 @@ -6,7 +6,8 @@

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 @@ -589,3 +590,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)