Skip to content

DEPR: to_timedelta box kwarg #30177

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 4 commits into from
Dec 11, 2019
Merged
Show file tree
Hide file tree
Changes from 1 commit
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.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -540,6 +540,7 @@ or ``matplotlib.Axes.plot``. See :ref:`plotting.formatters` for more.
- Changed the the default value of `inplace` in :meth:`DataFrame.set_index` and :meth:`Series.set_axis`. It now defaults to ``False`` (:issue:`27600`)
- Removed the previously deprecated :attr:`Series.cat.categorical`, :attr:`Series.cat.index`, :attr:`Series.cat.name` (:issue:`24751`)
- :func:`to_datetime` no longer accepts "box" argument, always returns :class:`DatetimeIndex` or :class:`Index`, :class:`Series`, or :class:`DataFrame` (:issue:`24486`)
- :func:`to_timedelta` no longer accepts "box" argument, always returns :class:`TimedeltaIndex` or :class:`Index`, :class:`Series`, or :class:`DataFrame` (:issue:`24486`)
Copy link
Member

Choose a reason for hiding this comment

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

Can you combine this into the above, by saying "to_datetime and to_timedetal no longer accept .." ?

Copy link
Member Author

Choose a reason for hiding this comment

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

combined

- :func:`to_timedelta`, :class:`Timedelta`, and :class:`TimedeltaIndex` no longer allow "M", "y", or "Y" for the "unit" argument (:issue:`23264`)
- Removed the previously deprecated ``time_rule`` keyword from (non-public) :func:`offsets.generate_range`, which has been moved to :func:`core.arrays._ranges.generate_range` (:issue:`24157`)
- :meth:`DataFrame.loc` or :meth:`Series.loc` with listlike indexers and missing labels will no longer reindex (:issue:`17295`)
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/dtypes/dtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -669,7 +669,7 @@ def __init__(self, unit="ns", tz=None):
tz = result.tz
msg = (
"Passing a dtype alias like 'datetime64[ns, {tz}]' "
"to DatetimeTZDtype is deprecated. Use "
"to DatetimeTZDtype is no longer supported. Use "
"'DatetimeTZDtype.construct_from_string()' instead."
)
raise ValueError(msg)
Expand Down
28 changes: 0 additions & 28 deletions pandas/core/indexes/datetimes.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,31 +108,6 @@ class DatetimeIndex(DatetimeIndexOpsMixin, Int64Index, DatetimeDelegateMixin):
One of pandas date offset strings or corresponding objects. The string
'infer' can be passed in order to set the frequency of the index as the
inferred frequency upon creation.

start : starting value, datetime-like, optional
If data is None, start is used as the start point in generating regular
timestamp data.

.. deprecated:: 0.24.0

periods : int, optional, > 0
Number of periods to generate, if generating index. Takes precedence
over end argument.

.. deprecated:: 0.24.0

end : end time, datetime-like, optional
If periods is none, generated index will extend to first conforming
time on or just past end argument.

.. deprecated:: 0.24.0

closed : str or None, default None
Make the interval closed with respect to the given frequency to
the 'left', 'right', or both sides (None).

.. deprecated:: 0.24. 0

tz : pytz.timezone or dateutil.tz.tzfile
ambiguous : 'infer', bool-ndarray, 'NaT', default 'raise'
When clocks moved backward due to DST, ambiguous times may arise.
Expand Down Expand Up @@ -217,9 +192,6 @@ class DatetimeIndex(DatetimeIndexOpsMixin, Int64Index, DatetimeDelegateMixin):
-----
To learn more about the frequency strings, please see `this link
<http://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases>`__.

Creating a DatetimeIndex based on `start`, `periods`, and `end` has
been deprecated in favor of :func:`date_range`.
"""

_typ = "datetimeindex"
Expand Down
5 changes: 0 additions & 5 deletions pandas/core/indexes/multi.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,11 +157,6 @@ class MultiIndex(Index):
Integers for each level designating which label at each location.

.. versionadded:: 0.24.0
labels : sequence of arrays
Integers for each level designating which label at each location.

.. deprecated:: 0.24.0
Use ``codes`` instead
sortorder : optional int
Level of sortedness (must be lexicographically sorted by that
level).
Expand Down
23 changes: 0 additions & 23 deletions pandas/core/indexes/period.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,24 +91,6 @@ class PeriodIndex(DatetimeIndexOpsMixin, Int64Index, PeriodDelegateMixin):
Make a copy of input ndarray
freq : str or period object, optional
One of pandas period strings or corresponding objects
start : starting value, period-like, optional
If data is None, used as the start point in generating regular
period data.

.. deprecated:: 0.24.0

periods : int, optional, > 0
Number of periods to generate, if generating index. Takes precedence
over end argument

.. deprecated:: 0.24.0

end : end value, period-like, optional
If periods is none, generated index will extend to first conforming
period on or just past end argument

.. deprecated:: 0.24.0

year : int, array, or Series, default None
month : int, array, or Series, default None
quarter : int, array, or Series, default None
Expand Down Expand Up @@ -157,11 +139,6 @@ class PeriodIndex(DatetimeIndexOpsMixin, Int64Index, PeriodDelegateMixin):
TimedeltaIndex : Index of timedelta64 data.
period_range : Create a fixed-frequency PeriodIndex.

Notes
-----
Creating a PeriodIndex based on `start`, `periods`, and `end` has
been deprecated in favor of :func:`period_range`.

Examples
--------
>>> idx = pd.PeriodIndex(year=year_arr, quarter=q_arr)
Expand Down
27 changes: 0 additions & 27 deletions pandas/core/indexes/timedeltas.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,30 +82,6 @@ class TimedeltaIndex(
inferred frequency upon creation.
copy : bool
Make a copy of input ndarray.
start : starting value, timedelta-like, optional
If data is None, start is used as the start point in generating regular
timedelta data.

.. deprecated:: 0.24.0

periods : int, optional, > 0
Number of periods to generate, if generating index. Takes precedence
over end argument.

.. deprecated:: 0.24.0

end : end time, timedelta-like, optional
If periods is none, generated index will extend to first conforming
time on or just past end argument.

.. deprecated:: 0.24. 0

closed : str or None, default None
Make the interval closed with respect to the given frequency to
the 'left', 'right', or both sides (None).

.. deprecated:: 0.24. 0

name : object
Name to be stored in the index.

Expand Down Expand Up @@ -140,9 +116,6 @@ class TimedeltaIndex(
-----
To learn more about the frequency strings, please see `this link
<http://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases>`__.

Creating a TimedeltaIndex based on `start`, `periods`, and `end` has
been deprecated in favor of :func:`timedelta_range`.
"""

_typ = "timedeltaindex"
Expand Down
38 changes: 9 additions & 29 deletions pandas/core/tools/timedeltas.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,14 @@

from pandas._libs.tslibs import NaT
from pandas._libs.tslibs.timedeltas import Timedelta, parse_timedelta_unit
from pandas.util._decorators import deprecate_kwarg

from pandas.core.dtypes.common import is_list_like
from pandas.core.dtypes.generic import ABCIndexClass, ABCSeries

from pandas.core.arrays.timedeltas import sequence_to_td64ns


@deprecate_kwarg(old_arg_name="box", new_arg_name=None)
def to_timedelta(arg, unit="ns", box=True, errors="raise"):
def to_timedelta(arg, unit="ns", errors="raise"):
"""
Convert argument to timedelta.

Expand All @@ -36,15 +34,6 @@ def to_timedelta(arg, unit="ns", box=True, errors="raise"):
'milli', 'millis', 'L', 'us', 'microseconds', 'microsecond',
'micro', 'micros', 'U', 'ns', 'nanoseconds', 'nano', 'nanos',
'nanosecond', 'N').
box : bool, default True
- If True returns a Timedelta/TimedeltaIndex of the results.
- If False returns a numpy.timedelta64 or numpy.darray of
values of dtype timedelta64[ns].

.. deprecated:: 0.25.0
Use :meth:`Series.to_numpy` or :meth:`Timedelta.to_timedelta64`
instead to get an ndarray of values or numpy.timedelta64,
respectively.

errors : {'ignore', 'raise', 'coerce'}, default 'raise'
- If 'raise', then invalid parsing will raise an exception.
Expand Down Expand Up @@ -86,11 +75,6 @@ def to_timedelta(arg, unit="ns", box=True, errors="raise"):
>>> pd.to_timedelta(np.arange(5), unit='d')
TimedeltaIndex(['0 days', '1 days', '2 days', '3 days', '4 days'],
dtype='timedelta64[ns]', freq=None)

Returning an ndarray by using the 'box' keyword argument:

>>> pd.to_timedelta(np.arange(5), box=False)
array([0, 1, 2, 3, 4], dtype='timedelta64[ns]')
"""
unit = parse_timedelta_unit(unit)

Expand All @@ -106,32 +90,29 @@ def to_timedelta(arg, unit="ns", box=True, errors="raise"):
if arg is None:
return arg
elif isinstance(arg, ABCSeries):
values = _convert_listlike(arg._values, unit=unit, box=False, errors=errors)
values = _convert_listlike(arg._values, unit=unit, errors=errors)
return arg._constructor(values, index=arg.index, name=arg.name)
elif isinstance(arg, ABCIndexClass):
return _convert_listlike(arg, unit=unit, box=box, errors=errors, name=arg.name)
return _convert_listlike(arg, unit=unit, errors=errors, name=arg.name)
elif isinstance(arg, np.ndarray) and arg.ndim == 0:
# extract array scalar and process below
arg = arg.item()
elif is_list_like(arg) and getattr(arg, "ndim", 1) == 1:
return _convert_listlike(arg, unit=unit, box=box, errors=errors)
return _convert_listlike(arg, unit=unit, errors=errors)
elif getattr(arg, "ndim", 1) > 1:
raise TypeError(
"arg must be a string, timedelta, list, tuple, 1-d array, or Series"
)

# ...so it must be a scalar value. Return scalar.
return _coerce_scalar_to_timedelta_type(arg, unit=unit, box=box, errors=errors)
return _coerce_scalar_to_timedelta_type(arg, unit=unit, errors=errors)


def _coerce_scalar_to_timedelta_type(r, unit="ns", box=True, errors="raise"):
def _coerce_scalar_to_timedelta_type(r, unit="ns", errors="raise"):
"""Convert string 'r' to a timedelta object."""

try:
result = Timedelta(r, unit)
if not box:
# explicitly view as timedelta64 for case when result is pd.NaT
result = result.asm8.view("timedelta64[ns]")
except ValueError:
if errors == "raise":
raise
Expand All @@ -144,7 +125,7 @@ def _coerce_scalar_to_timedelta_type(r, unit="ns", box=True, errors="raise"):
return result


def _convert_listlike(arg, unit="ns", box=True, errors="raise", name=None):
def _convert_listlike(arg, unit="ns", errors="raise", name=None):
"""Convert a list of objects to a timedelta index object."""

if isinstance(arg, (list, tuple)) or not hasattr(arg, "dtype"):
Expand All @@ -169,8 +150,7 @@ def _convert_listlike(arg, unit="ns", box=True, errors="raise", name=None):
# like to surface it.
raise

if box:
from pandas import TimedeltaIndex
from pandas import TimedeltaIndex

value = TimedeltaIndex(value, unit="ns", name=name)
value = TimedeltaIndex(value, unit="ns", name=name)
return value
5 changes: 0 additions & 5 deletions pandas/io/excel/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,11 +79,6 @@
is based on the subset.
usecols : int, str, list-like, or callable default None
* If None, then parse all columns.
* If int, then indicates last column to be parsed.

.. deprecated:: 0.24.0
Pass in a list of int instead from 0 to `usecols` inclusive.

* If str, then indicates comma separated list of Excel column letters
and column ranges (e.g. "A:E" or "A,C,E:F"). Ranges are inclusive of
both sides.
Expand Down
10 changes: 0 additions & 10 deletions pandas/tests/indexes/timedeltas/test_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -208,13 +208,3 @@ def test_to_timedelta_float(self):
result = pd.to_timedelta(arr, unit="s")
expected_asi8 = np.arange(999990000, int(1e9), 1000, dtype="int64")
tm.assert_numpy_array_equal(result.asi8, expected_asi8)

def test_to_timedelta_box_deprecated(self):
result = np.timedelta64(0, "ns")

# Deprecated - see GH24416
with tm.assert_produces_warning(FutureWarning):
to_timedelta(0, box=False)

expected = to_timedelta(0).to_timedelta64()
assert result == expected