Skip to content

Commit 1d50235

Browse files
jbrockmendelproost
authored andcommitted
DEPR: to_timedelta box kwarg (pandas-dev#30177)
1 parent f003df3 commit 1d50235

File tree

9 files changed

+11
-192
lines changed

9 files changed

+11
-192
lines changed

doc/source/whatsnew/v1.0.0.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -541,7 +541,7 @@ or ``matplotlib.Axes.plot``. See :ref:`plotting.formatters` for more.
541541
- Removed the previously deprecated :meth:`Series.compound` and :meth:`DataFrame.compound` (:issue:`26405`)
542542
- Changed the the default value of `inplace` in :meth:`DataFrame.set_index` and :meth:`Series.set_axis`. It now defaults to ``False`` (:issue:`27600`)
543543
- Removed the previously deprecated :attr:`Series.cat.categorical`, :attr:`Series.cat.index`, :attr:`Series.cat.name` (:issue:`24751`)
544-
- :func:`to_datetime` no longer accepts "box" argument, always returns :class:`DatetimeIndex` or :class:`Index`, :class:`Series`, or :class:`DataFrame` (:issue:`24486`)
544+
- :func:`to_datetime` and :func:`to_timedelta` no longer accept "box" argument, always returns :class:`DatetimeIndex`, :class:`TimedeltaIndex`, :class:`Index`, :class:`Series`, or :class:`DataFrame` (:issue:`24486`)
545545
- :func:`to_timedelta`, :class:`Timedelta`, and :class:`TimedeltaIndex` no longer allow "M", "y", or "Y" for the "unit" argument (:issue:`23264`)
546546
- 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`)
547547
- :meth:`DataFrame.loc` or :meth:`Series.loc` with listlike indexers and missing labels will no longer reindex (:issue:`17295`)

pandas/core/dtypes/dtypes.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -669,7 +669,7 @@ def __init__(self, unit="ns", tz=None):
669669
tz = result.tz
670670
msg = (
671671
"Passing a dtype alias like 'datetime64[ns, {tz}]' "
672-
"to DatetimeTZDtype is deprecated. Use "
672+
"to DatetimeTZDtype is no longer supported. Use "
673673
"'DatetimeTZDtype.construct_from_string()' instead."
674674
)
675675
raise ValueError(msg)

pandas/core/indexes/datetimes.py

-28
Original file line numberDiff line numberDiff line change
@@ -108,31 +108,6 @@ class DatetimeIndex(DatetimeIndexOpsMixin, Int64Index, DatetimeDelegateMixin):
108108
One of pandas date offset strings or corresponding objects. The string
109109
'infer' can be passed in order to set the frequency of the index as the
110110
inferred frequency upon creation.
111-
112-
start : starting value, datetime-like, optional
113-
If data is None, start is used as the start point in generating regular
114-
timestamp data.
115-
116-
.. deprecated:: 0.24.0
117-
118-
periods : int, optional, > 0
119-
Number of periods to generate, if generating index. Takes precedence
120-
over end argument.
121-
122-
.. deprecated:: 0.24.0
123-
124-
end : end time, datetime-like, optional
125-
If periods is none, generated index will extend to first conforming
126-
time on or just past end argument.
127-
128-
.. deprecated:: 0.24.0
129-
130-
closed : str or None, default None
131-
Make the interval closed with respect to the given frequency to
132-
the 'left', 'right', or both sides (None).
133-
134-
.. deprecated:: 0.24. 0
135-
136111
tz : pytz.timezone or dateutil.tz.tzfile
137112
ambiguous : 'infer', bool-ndarray, 'NaT', default 'raise'
138113
When clocks moved backward due to DST, ambiguous times may arise.
@@ -217,9 +192,6 @@ class DatetimeIndex(DatetimeIndexOpsMixin, Int64Index, DatetimeDelegateMixin):
217192
-----
218193
To learn more about the frequency strings, please see `this link
219194
<http://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases>`__.
220-
221-
Creating a DatetimeIndex based on `start`, `periods`, and `end` has
222-
been deprecated in favor of :func:`date_range`.
223195
"""
224196

225197
_typ = "datetimeindex"

pandas/core/indexes/multi.py

-5
Original file line numberDiff line numberDiff line change
@@ -157,11 +157,6 @@ class MultiIndex(Index):
157157
Integers for each level designating which label at each location.
158158
159159
.. versionadded:: 0.24.0
160-
labels : sequence of arrays
161-
Integers for each level designating which label at each location.
162-
163-
.. deprecated:: 0.24.0
164-
Use ``codes`` instead
165160
sortorder : optional int
166161
Level of sortedness (must be lexicographically sorted by that
167162
level).

pandas/core/indexes/period.py

-23
Original file line numberDiff line numberDiff line change
@@ -91,24 +91,6 @@ class PeriodIndex(DatetimeIndexOpsMixin, Int64Index, PeriodDelegateMixin):
9191
Make a copy of input ndarray
9292
freq : str or period object, optional
9393
One of pandas period strings or corresponding objects
94-
start : starting value, period-like, optional
95-
If data is None, used as the start point in generating regular
96-
period data.
97-
98-
.. deprecated:: 0.24.0
99-
100-
periods : int, optional, > 0
101-
Number of periods to generate, if generating index. Takes precedence
102-
over end argument
103-
104-
.. deprecated:: 0.24.0
105-
106-
end : end value, period-like, optional
107-
If periods is none, generated index will extend to first conforming
108-
period on or just past end argument
109-
110-
.. deprecated:: 0.24.0
111-
11294
year : int, array, or Series, default None
11395
month : int, array, or Series, default None
11496
quarter : int, array, or Series, default None
@@ -157,11 +139,6 @@ class PeriodIndex(DatetimeIndexOpsMixin, Int64Index, PeriodDelegateMixin):
157139
TimedeltaIndex : Index of timedelta64 data.
158140
period_range : Create a fixed-frequency PeriodIndex.
159141
160-
Notes
161-
-----
162-
Creating a PeriodIndex based on `start`, `periods`, and `end` has
163-
been deprecated in favor of :func:`period_range`.
164-
165142
Examples
166143
--------
167144
>>> idx = pd.PeriodIndex(year=year_arr, quarter=q_arr)

pandas/core/indexes/timedeltas.py

-27
Original file line numberDiff line numberDiff line change
@@ -82,30 +82,6 @@ class TimedeltaIndex(
8282
inferred frequency upon creation.
8383
copy : bool
8484
Make a copy of input ndarray.
85-
start : starting value, timedelta-like, optional
86-
If data is None, start is used as the start point in generating regular
87-
timedelta data.
88-
89-
.. deprecated:: 0.24.0
90-
91-
periods : int, optional, > 0
92-
Number of periods to generate, if generating index. Takes precedence
93-
over end argument.
94-
95-
.. deprecated:: 0.24.0
96-
97-
end : end time, timedelta-like, optional
98-
If periods is none, generated index will extend to first conforming
99-
time on or just past end argument.
100-
101-
.. deprecated:: 0.24. 0
102-
103-
closed : str or None, default None
104-
Make the interval closed with respect to the given frequency to
105-
the 'left', 'right', or both sides (None).
106-
107-
.. deprecated:: 0.24. 0
108-
10985
name : object
11086
Name to be stored in the index.
11187
@@ -140,9 +116,6 @@ class TimedeltaIndex(
140116
-----
141117
To learn more about the frequency strings, please see `this link
142118
<http://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases>`__.
143-
144-
Creating a TimedeltaIndex based on `start`, `periods`, and `end` has
145-
been deprecated in favor of :func:`timedelta_range`.
146119
"""
147120

148121
_typ = "timedeltaindex"

pandas/core/tools/timedeltas.py

+9-29
Original file line numberDiff line numberDiff line change
@@ -6,16 +6,14 @@
66

77
from pandas._libs.tslibs import NaT
88
from pandas._libs.tslibs.timedeltas import Timedelta, parse_timedelta_unit
9-
from pandas.util._decorators import deprecate_kwarg
109

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

1413
from pandas.core.arrays.timedeltas import sequence_to_td64ns
1514

1615

17-
@deprecate_kwarg(old_arg_name="box", new_arg_name=None)
18-
def to_timedelta(arg, unit="ns", box=True, errors="raise"):
16+
def to_timedelta(arg, unit="ns", errors="raise"):
1917
"""
2018
Convert argument to timedelta.
2119
@@ -36,15 +34,6 @@ def to_timedelta(arg, unit="ns", box=True, errors="raise"):
3634
'milli', 'millis', 'L', 'us', 'microseconds', 'microsecond',
3735
'micro', 'micros', 'U', 'ns', 'nanoseconds', 'nano', 'nanos',
3836
'nanosecond', 'N').
39-
box : bool, default True
40-
- If True returns a Timedelta/TimedeltaIndex of the results.
41-
- If False returns a numpy.timedelta64 or numpy.darray of
42-
values of dtype timedelta64[ns].
43-
44-
.. deprecated:: 0.25.0
45-
Use :meth:`Series.to_numpy` or :meth:`Timedelta.to_timedelta64`
46-
instead to get an ndarray of values or numpy.timedelta64,
47-
respectively.
4837
4938
errors : {'ignore', 'raise', 'coerce'}, default 'raise'
5039
- If 'raise', then invalid parsing will raise an exception.
@@ -86,11 +75,6 @@ def to_timedelta(arg, unit="ns", box=True, errors="raise"):
8675
>>> pd.to_timedelta(np.arange(5), unit='d')
8776
TimedeltaIndex(['0 days', '1 days', '2 days', '3 days', '4 days'],
8877
dtype='timedelta64[ns]', freq=None)
89-
90-
Returning an ndarray by using the 'box' keyword argument:
91-
92-
>>> pd.to_timedelta(np.arange(5), box=False)
93-
array([0, 1, 2, 3, 4], dtype='timedelta64[ns]')
9478
"""
9579
unit = parse_timedelta_unit(unit)
9680

@@ -106,32 +90,29 @@ def to_timedelta(arg, unit="ns", box=True, errors="raise"):
10690
if arg is None:
10791
return arg
10892
elif isinstance(arg, ABCSeries):
109-
values = _convert_listlike(arg._values, unit=unit, box=False, errors=errors)
93+
values = _convert_listlike(arg._values, unit=unit, errors=errors)
11094
return arg._constructor(values, index=arg.index, name=arg.name)
11195
elif isinstance(arg, ABCIndexClass):
112-
return _convert_listlike(arg, unit=unit, box=box, errors=errors, name=arg.name)
96+
return _convert_listlike(arg, unit=unit, errors=errors, name=arg.name)
11397
elif isinstance(arg, np.ndarray) and arg.ndim == 0:
11498
# extract array scalar and process below
11599
arg = arg.item()
116100
elif is_list_like(arg) and getattr(arg, "ndim", 1) == 1:
117-
return _convert_listlike(arg, unit=unit, box=box, errors=errors)
101+
return _convert_listlike(arg, unit=unit, errors=errors)
118102
elif getattr(arg, "ndim", 1) > 1:
119103
raise TypeError(
120104
"arg must be a string, timedelta, list, tuple, 1-d array, or Series"
121105
)
122106

123107
# ...so it must be a scalar value. Return scalar.
124-
return _coerce_scalar_to_timedelta_type(arg, unit=unit, box=box, errors=errors)
108+
return _coerce_scalar_to_timedelta_type(arg, unit=unit, errors=errors)
125109

126110

127-
def _coerce_scalar_to_timedelta_type(r, unit="ns", box=True, errors="raise"):
111+
def _coerce_scalar_to_timedelta_type(r, unit="ns", errors="raise"):
128112
"""Convert string 'r' to a timedelta object."""
129113

130114
try:
131115
result = Timedelta(r, unit)
132-
if not box:
133-
# explicitly view as timedelta64 for case when result is pd.NaT
134-
result = result.asm8.view("timedelta64[ns]")
135116
except ValueError:
136117
if errors == "raise":
137118
raise
@@ -144,7 +125,7 @@ def _coerce_scalar_to_timedelta_type(r, unit="ns", box=True, errors="raise"):
144125
return result
145126

146127

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

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

172-
if box:
173-
from pandas import TimedeltaIndex
153+
from pandas import TimedeltaIndex
174154

175-
value = TimedeltaIndex(value, unit="ns", name=name)
155+
value = TimedeltaIndex(value, unit="ns", name=name)
176156
return value

pandas/io/excel/_base.py

-5
Original file line numberDiff line numberDiff line change
@@ -79,11 +79,6 @@
7979
is based on the subset.
8080
usecols : int, str, list-like, or callable default None
8181
* If None, then parse all columns.
82-
* If int, then indicates last column to be parsed.
83-
84-
.. deprecated:: 0.24.0
85-
Pass in a list of int instead from 0 to `usecols` inclusive.
86-
8782
* If str, then indicates comma separated list of Excel column letters
8883
and column ranges (e.g. "A:E" or "A,C,E:F"). Ranges are inclusive of
8984
both sides.

pandas/tests/indexes/timedeltas/test_tools.py

-73
Original file line numberDiff line numberDiff line change
@@ -3,35 +3,13 @@
33
import numpy as np
44
import pytest
55

6-
from pandas._libs.tslib import iNaT
7-
86
import pandas as pd
97
from pandas import Series, TimedeltaIndex, isna, to_timedelta
108
import pandas.util.testing as tm
119

1210

1311
class TestTimedeltas:
1412
def test_to_timedelta(self):
15-
def conv(v):
16-
return v.astype("m8[ns]")
17-
18-
d1 = np.timedelta64(1, "D")
19-
20-
with tm.assert_produces_warning(FutureWarning):
21-
assert to_timedelta("1 days 06:05:01.00003", box=False) == conv(
22-
d1
23-
+ np.timedelta64(6 * 3600 + 5 * 60 + 1, "s")
24-
+ np.timedelta64(30, "us")
25-
)
26-
27-
with tm.assert_produces_warning(FutureWarning):
28-
assert to_timedelta("15.5us", box=False) == conv(
29-
np.timedelta64(15500, "ns")
30-
)
31-
32-
# empty string
33-
result = to_timedelta("", box=False)
34-
assert result.astype("int64") == iNaT
3513

3614
result = to_timedelta(["", ""])
3715
assert isna(result).all()
@@ -41,12 +19,6 @@ def conv(v):
4119
expected = pd.Index(np.array([np.timedelta64(1, "s")]))
4220
tm.assert_index_equal(result, expected)
4321

44-
with tm.assert_produces_warning(FutureWarning):
45-
# ints
46-
result = np.timedelta64(0, "ns")
47-
expected = to_timedelta(0, box=False)
48-
assert result == expected
49-
5022
# Series
5123
expected = Series([timedelta(days=1), timedelta(days=1, seconds=1)])
5224
result = to_timedelta(Series(["1d", "1days 00:00:01"]))
@@ -59,19 +31,6 @@ def conv(v):
5931
expected = to_timedelta([0, 10], unit="s")
6032
tm.assert_index_equal(result, expected)
6133

62-
with tm.assert_produces_warning(FutureWarning):
63-
# single element conversion
64-
v = timedelta(seconds=1)
65-
result = to_timedelta(v, box=False)
66-
expected = np.timedelta64(timedelta(seconds=1))
67-
assert result == expected
68-
69-
with tm.assert_produces_warning(FutureWarning):
70-
v = np.timedelta64(timedelta(seconds=1))
71-
result = to_timedelta(v, box=False)
72-
expected = np.timedelta64(timedelta(seconds=1))
73-
assert result == expected
74-
7534
# arrays of various dtypes
7635
arr = np.array([1] * 5, dtype="int64")
7736
result = to_timedelta(arr, unit="s")
@@ -98,28 +57,6 @@ def conv(v):
9857
expected = TimedeltaIndex([np.timedelta64(1, "D")] * 5)
9958
tm.assert_index_equal(result, expected)
10059

101-
with tm.assert_produces_warning(FutureWarning):
102-
# Test with lists as input when box=false
103-
expected = np.array(np.arange(3) * 1000000000, dtype="timedelta64[ns]")
104-
result = to_timedelta(range(3), unit="s", box=False)
105-
tm.assert_numpy_array_equal(expected, result)
106-
107-
with tm.assert_produces_warning(FutureWarning):
108-
result = to_timedelta(np.arange(3), unit="s", box=False)
109-
tm.assert_numpy_array_equal(expected, result)
110-
111-
with tm.assert_produces_warning(FutureWarning):
112-
result = to_timedelta([0, 1, 2], unit="s", box=False)
113-
tm.assert_numpy_array_equal(expected, result)
114-
115-
with tm.assert_produces_warning(FutureWarning):
116-
# Tests with fractional seconds as input:
117-
expected = np.array(
118-
[0, 500000000, 800000000, 1200000000], dtype="timedelta64[ns]"
119-
)
120-
result = to_timedelta([0.0, 0.5, 0.8, 1.2], unit="s", box=False)
121-
tm.assert_numpy_array_equal(expected, result)
122-
12360
def test_to_timedelta_invalid(self):
12461

12562
# bad value for errors parameter
@@ -208,13 +145,3 @@ def test_to_timedelta_float(self):
208145
result = pd.to_timedelta(arr, unit="s")
209146
expected_asi8 = np.arange(999990000, int(1e9), 1000, dtype="int64")
210147
tm.assert_numpy_array_equal(result.asi8, expected_asi8)
211-
212-
def test_to_timedelta_box_deprecated(self):
213-
result = np.timedelta64(0, "ns")
214-
215-
# Deprecated - see GH24416
216-
with tm.assert_produces_warning(FutureWarning):
217-
to_timedelta(0, box=False)
218-
219-
expected = to_timedelta(0).to_timedelta64()
220-
assert result == expected

0 commit comments

Comments
 (0)