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

DEPR: deprecate integer add/sub with DTI/TDI/PI/Timestamp/Period #22535

Merged
merged 40 commits into from
Nov 1, 2018
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
Show all changes
40 commits
Select commit Hold shift + click to select a range
145eb6a
DEPR: deprecate integer add/sub with DTI/TDI/PI/Timestamp/Period
jbrockmendel Aug 29, 2018
d5c5f28
say future version instead of a specific version number
jbrockmendel Aug 29, 2018
3fb29bc
Merge branch 'master' of https://github.com/pandas-dev/pandas into in…
jbrockmendel Aug 31, 2018
81c9eab
typo fixup
jbrockmendel Aug 31, 2018
26c9966
Catch FutureWarning/PerformanceWarning in tests
jbrockmendel Sep 1, 2018
11959b1
Merge branch 'master' of https://github.com/pandas-dev/pandas into in…
jbrockmendel Sep 5, 2018
8952cb5
set stacklevel
jbrockmendel Sep 5, 2018
7c79364
Merge branch 'master' of https://github.com/pandas-dev/pandas into in…
jbrockmendel Sep 7, 2018
d0fa41a
Avoid warnings in plotting._converter
jbrockmendel Sep 7, 2018
c23346b
Merge branch 'master' of https://github.com/pandas-dev/pandas into in…
jbrockmendel Sep 7, 2018
f6daf34
Merge branch 'master' of https://github.com/pandas-dev/pandas into in…
jbrockmendel Sep 9, 2018
b7e3dcf
Fixup flipped condition
jbrockmendel Sep 9, 2018
2a829d3
Merge branch 'master' of https://github.com/pandas-dev/pandas into in…
jbrockmendel Sep 28, 2018
f24643c
whatsnew section on deprecation
jbrockmendel Sep 28, 2018
6fea2a8
Merge branch 'master' of https://github.com/pandas-dev/pandas into in…
jbrockmendel Oct 4, 2018
b469bef
just input in whatsnew executable block
jbrockmendel Oct 4, 2018
20d58fa
Catch warnings in tests
jbrockmendel Oct 4, 2018
984bc7e
TST: catch warnings for strict test run
jbrockmendel Oct 4, 2018
841718c
Merge branch 'master' of https://github.com/pandas-dev/pandas into in…
jbrockmendel Oct 5, 2018
7e7a348
Catch warnings
jbrockmendel Oct 5, 2018
17f6be0
Avoid warnings
jbrockmendel Oct 5, 2018
29cca46
catch more warnings
jbrockmendel Oct 5, 2018
b0a222a
avoid warning
jbrockmendel Oct 5, 2018
14b9eaf
Merge branch 'master' of https://github.com/pandas-dev/pandas into in…
jbrockmendel Oct 15, 2018
55dc265
Avoid need to catch deprecation warnings
jbrockmendel Oct 15, 2018
9443df9
stop using deprecated usage
jbrockmendel Oct 15, 2018
d46452d
Merge branch 'master' of https://github.com/pandas-dev/pandas into in…
jbrockmendel Oct 17, 2018
af31b0c
Merge branch 'master' of https://github.com/pandas-dev/pandas into in…
jbrockmendel Oct 18, 2018
0bebbe0
Merge branch 'master' of https://github.com/pandas-dev/pandas into in…
jbrockmendel Oct 28, 2018
c7dd7ce
update to user PeriodArray private method
jbrockmendel Oct 29, 2018
ca55b4a
Merge branch 'master' of https://github.com/pandas-dev/pandas into in…
jbrockmendel Oct 29, 2018
394a3b8
suppress
jbrockmendel Oct 29, 2018
3884bb4
Merge branch 'master' of https://github.com/pandas-dev/pandas into in…
jbrockmendel Oct 29, 2018
a15d9e4
Merge branch 'master' of https://github.com/pandas-dev/pandas into in…
jbrockmendel Oct 30, 2018
5256671
function for warning
jbrockmendel Oct 30, 2018
d8865d7
ignore stacklevel
jbrockmendel Oct 30, 2018
da72660
Merge branch 'master' of https://github.com/pandas-dev/pandas into in…
jbrockmendel Oct 31, 2018
fcd65b3
Show deprecation warning in whatsnew
jbrockmendel Oct 31, 2018
6ded8b1
move location of addsub_int_array warning
jbrockmendel Oct 31, 2018
4a7b589
rename deprecation warning function
jbrockmendel Oct 31, 2018
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
2 changes: 2 additions & 0 deletions doc/source/whatsnew/v0.24.0.txt
Original file line number Diff line number Diff line change
Expand Up @@ -556,6 +556,8 @@ Deprecations
- :func:`pandas.read_table` is deprecated. Instead, use :func:`pandas.read_csv` passing ``sep='\t'`` if necessary (:issue:`21948`)
- :meth:`Series.str.cat` has deprecated using arbitrary list-likes *within* list-likes. A list-like container may still contain
many ``Series``, ``Index`` or 1-dimensional ``np.ndarray``, or alternatively, only scalar values. (:issue:`21950`)
- Addition or subtraction of integers with :class:`Timestamp`, :class:`Period`, :class:`DatetimeIndex`, :class:`TimedeltaIndex`, :class:`PeriodIndex` is deprecated, will be removed in a future version (:issue:`21939`)
Copy link
Contributor

Choose a reason for hiding this comment

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

pls make a sub-section and show what is being deprecated and what is the alternative. this is actually a rather large change.

Copy link
Member Author

Choose a reason for hiding this comment

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

I'll try to get to this tomorrow.

Copy link
Member Author

Choose a reason for hiding this comment

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

@jreback just added this section; wasn't sure on where in the doc to put it and the ipython/code-block syntax is a shot in the dark. Please advise.

- Addition or subtraction of integer-dtyped arrays with :class:`DatetimeIndex`, :class:`TimedeltaIndex`, :class:`PeriodIndex` is deprecated, will be removed in a future version (:issue:`21939`)

.. _whatsnew_0240.prior_deprecations:

Expand Down
20 changes: 18 additions & 2 deletions pandas/_libs/tslibs/period.pyx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# -*- coding: utf-8 -*-
from datetime import datetime, date
import warnings

from cpython cimport (
PyUnicode_Check,
Expand Down Expand Up @@ -1645,6 +1646,13 @@ cdef class _Period(object):
elif other is NaT:
return NaT
elif util.is_integer_object(other):
warnings.warn("Addition of integers to {cls} is "
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 call a function for this warning (not sure exatcly where), rather than repeating each time, prob need to pass in the level

Copy link
Member Author

Choose a reason for hiding this comment

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

Not sure what you have in mind. Just a one-liner containing this warning?

Copy link
Contributor

Choose a reason for hiding this comment

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

yeah a module level function just seems better than copy-pasting

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 do this

"deprecated, will be removed in a future "
"version. Instead of adding `n`, add "
"`n * self.freq`"
.format(cls=type(self).__name__),
FutureWarning)

ordinal = self.ordinal + other * self.freq.n
return Period(ordinal=ordinal, freq=self.freq)
elif (PyDateTime_Check(other) or
Expand All @@ -1671,6 +1679,13 @@ cdef class _Period(object):
neg_other = -other
return self + neg_other
elif util.is_integer_object(other):
warnings.warn("Subtraction of integers from {cls} is "
"deprecated, will be removed in a future "
"version. Instead of subtracting `n`, subtract "
"`n * self.freq`"
.format(cls=type(self).__name__),
FutureWarning)

ordinal = self.ordinal - other * self.freq.n
return Period(ordinal=ordinal, freq=self.freq)
elif is_period_object(other):
Expand Down Expand Up @@ -1756,7 +1771,7 @@ cdef class _Period(object):
def end_time(self):
# freq.n can't be negative or 0
# ordinal = (self + self.freq.n).start_time.value - 1
ordinal = (self + 1).start_time.value - 1
ordinal = (self + self.freq).start_time.value - 1
return Timestamp(ordinal)

def to_timestamp(self, freq=None, how='start', tz=None):
Expand All @@ -1783,7 +1798,8 @@ cdef class _Period(object):

end = how == 'E'
if end:
return (self + 1).to_timestamp(how='start') - Timedelta(1, 'ns')
endpoint = (self + self.freq).to_timestamp(how='start')
return endpoint - Timedelta(1, 'ns')

if freq is None:
base, mult = get_freq_code(self.freq)
Expand Down
11 changes: 10 additions & 1 deletion pandas/_libs/tslibs/timestamps.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -250,14 +250,23 @@ cdef class _Timestamp(datetime):
return np.datetime64(self.value, 'ns')

def __add__(self, other):
cdef int64_t other_int, nanos
cdef:
int64_t other_int, nanos

if is_timedelta64_object(other):
other_int = other.astype('timedelta64[ns]').view('i8')
return Timestamp(self.value + other_int,
tz=self.tzinfo, freq=self.freq)

elif is_integer_object(other):
if self.freq is None:
Copy link
Contributor

Choose a reason for hiding this comment

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

is it necessary for freq to be none here? (we don't have this check elsewhere)

Copy link
Member Author

Choose a reason for hiding this comment

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

Should be not-None, good catch.

Copy link
Contributor

Choose a reason for hiding this comment

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

does this need to be changed?

warnings.warn("Addition of integers to {cls} is "
"deprecated, will be removed in a future "
"version. Instead of adding `n`, add "
"`n * self.freq`"
.format(cls=type(self).__name__),
FutureWarning)

if self is NaT:
# to be compat with Period
return NaT
Expand Down
32 changes: 32 additions & 0 deletions pandas/core/arrays/datetimelike.py
Original file line number Diff line number Diff line change
Expand Up @@ -466,6 +466,18 @@ def _addsub_int_array(self, other, op):
result : same class as self
"""
assert op in [operator.add, operator.sub]

if self.freq is not None:
# case with freq of None will raise
# we need to use a different stacklevel for Index vs Array
lvl = 3 + 1 * isinstance(self, ABCIndexClass)
warnings.warn("Addition/subtraction of integer array from {cls} "
"is deprecated, will be removed in a future "
"version. Instead of adding `arr`, "
"add `arr * self.freq`"
.format(cls=type(self).__name__),
FutureWarning, stacklevel=lvl)

if is_period_dtype(self):
# easy case for PeriodIndex
if op is operator.sub:
Expand Down Expand Up @@ -584,6 +596,16 @@ def __add__(self, other):
elif lib.is_integer(other):
# This check must come after the check for np.timedelta64
# as is_integer returns True for these
if self.freq is not None:
# case with freq of None will raise
# we need to use a different stacklevel for Index vs Array
lvl = 2 + 1 * isinstance(self, ABCIndexClass)
warnings.warn("Addition of integers to {cls} is "
"deprecated, will be removed in a future "
"version. Instead of adding `n`, "
"add `n * self.freq`"
.format(cls=type(self).__name__),
FutureWarning, stacklevel=lvl)
result = self.shift(other)

# array-like others
Expand Down Expand Up @@ -636,6 +658,16 @@ def __sub__(self, other):
elif lib.is_integer(other):
# This check must come after the check for np.timedelta64
# as is_integer returns True for these
if self.freq is not None:
# case with freq of None will raise
# we need to use a different stacklevel for Index vs Array
lvl = 2 + 1 * isinstance(self, ABCIndexClass)
warnings.warn("Subtraction of integers from {cls} is "
"deprecated, will be removed in a future "
"version. Instead of subtracting `n`, "
"subtract `n * self.freq`"
.format(cls=type(self).__name__),
FutureWarning, stacklevel=lvl)
result = self.shift(-other)
elif isinstance(other, Period):
result = self._sub_period(other)
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/resample.py
Original file line number Diff line number Diff line change
Expand Up @@ -1426,7 +1426,7 @@ def _get_time_delta_bins(self, ax):
freq=self.freq,
name=ax.name)

end_stamps = labels + 1
end_stamps = labels + self.freq
bins = ax.searchsorted(end_stamps, side='left')

# Addresses GH #10530
Expand Down
8 changes: 4 additions & 4 deletions pandas/plotting/_converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -583,7 +583,7 @@ def period_break(dates, period):
Name of the period to monitor.
"""
current = getattr(dates, period)
previous = getattr(dates - 1, period)
previous = getattr(dates - 1 * dates.freq, period)
return np.nonzero(current - previous)[0]


Expand Down Expand Up @@ -669,7 +669,7 @@ def first_label(label_flags):

def _hour_finder(label_interval, force_year_start):
_hour = dates_.hour
_prev_hour = (dates_ - 1).hour
_prev_hour = (dates_ - 1 * dates_.freq).hour
hour_start = (_hour - _prev_hour) != 0
info_maj[day_start] = True
info_min[hour_start & (_hour % label_interval == 0)] = True
Expand All @@ -683,7 +683,7 @@ def _hour_finder(label_interval, force_year_start):
def _minute_finder(label_interval):
hour_start = period_break(dates_, 'hour')
_minute = dates_.minute
_prev_minute = (dates_ - 1).minute
_prev_minute = (dates_ - 1 * dates_.freq).minute
minute_start = (_minute - _prev_minute) != 0
info_maj[hour_start] = True
info_min[minute_start & (_minute % label_interval == 0)] = True
Expand All @@ -696,7 +696,7 @@ def _minute_finder(label_interval):
def _second_finder(label_interval):
minute_start = period_break(dates_, 'minute')
_second = dates_.second
_prev_second = (dates_ - 1).second
_prev_second = (dates_ - 1 * dates_.freq).second
second_start = (_second - _prev_second) != 0
info['maj'][minute_start] = True
info['min'][second_start & (_second % label_interval == 0)] = True
Expand Down
59 changes: 41 additions & 18 deletions pandas/tests/arithmetic/test_datetime64.py
Original file line number Diff line number Diff line change
Expand Up @@ -1035,7 +1035,8 @@ def test_dti_add_int(self, tz_naive_fixture, one):
tz = tz_naive_fixture
rng = pd.date_range('2000-01-01 09:00', freq='H',
periods=10, tz=tz)
result = rng + one
with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
result = rng + one
expected = pd.date_range('2000-01-01 10:00', freq='H',
periods=10, tz=tz)
tm.assert_index_equal(result, expected)
Expand All @@ -1046,14 +1047,16 @@ def test_dti_iadd_int(self, tz_naive_fixture, one):
periods=10, tz=tz)
expected = pd.date_range('2000-01-01 10:00', freq='H',
periods=10, tz=tz)
rng += one
with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
Copy link
Contributor

Choose a reason for hiding this comment

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

why can't you check the stacklevel anymore?

Copy link
Member Author

Choose a reason for hiding this comment

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

We basically never did. I never got the stacklevel checks to pass in any consistent way.

rng += one
tm.assert_index_equal(rng, expected)

def test_dti_sub_int(self, tz_naive_fixture, one):
tz = tz_naive_fixture
rng = pd.date_range('2000-01-01 09:00', freq='H',
periods=10, tz=tz)
result = rng - one
with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
result = rng - one
expected = pd.date_range('2000-01-01 08:00', freq='H',
periods=10, tz=tz)
tm.assert_index_equal(result, expected)
Expand All @@ -1064,7 +1067,8 @@ def test_dti_isub_int(self, tz_naive_fixture, one):
periods=10, tz=tz)
expected = pd.date_range('2000-01-01 08:00', freq='H',
periods=10, tz=tz)
rng -= one
with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
rng -= one
tm.assert_index_equal(rng, expected)

# -------------------------------------------------------------
Expand All @@ -1077,9 +1081,11 @@ def test_dti_add_intarray_tick(self, box, freq):
dti = pd.date_range('2016-01-01', periods=2, freq=freq)
other = box([4, -1])
expected = DatetimeIndex([dti[n] + other[n] for n in range(len(dti))])
result = dti + other
with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
result = dti + other
tm.assert_index_equal(result, expected)
result = other + dti
with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
result = other + dti
tm.assert_index_equal(result, expected)

@pytest.mark.parametrize('freq', ['W', 'M', 'MS', 'Q'])
Expand All @@ -1089,10 +1095,17 @@ def test_dti_add_intarray_non_tick(self, box, freq):
dti = pd.date_range('2016-01-01', periods=2, freq=freq)
other = box([4, -1])
expected = DatetimeIndex([dti[n] + other[n] for n in range(len(dti))])
with tm.assert_produces_warning(PerformanceWarning):

# tm.assert_produces_warning does not handle cases where we expect
# two warnings, in this case PerformanceWarning and FutureWarning.
# Until that is fixed, we don't catch either
with warnings.catch_warnings():
warnings.simplefilter("ignore")
result = dti + other
tm.assert_index_equal(result, expected)
with tm.assert_produces_warning(PerformanceWarning):

with warnings.catch_warnings():
warnings.simplefilter("ignore")
result = other + dti
tm.assert_index_equal(result, expected)

Expand Down Expand Up @@ -1637,13 +1650,15 @@ def test_dti_add_offset_array(self, tz_naive_fixture):
dti = pd.date_range('2017-01-01', periods=2, tz=tz)
other = np.array([pd.offsets.MonthEnd(), pd.offsets.Day(n=2)])

with tm.assert_produces_warning(PerformanceWarning):
with tm.assert_produces_warning(PerformanceWarning,
clear=[pd.core.arrays.datetimelike]):
res = dti + other
expected = DatetimeIndex([dti[n] + other[n] for n in range(len(dti))],
name=dti.name, freq='infer')
tm.assert_index_equal(res, expected)

with tm.assert_produces_warning(PerformanceWarning):
with tm.assert_produces_warning(PerformanceWarning,
clear=[pd.core.arrays.datetimelike]):
res2 = other + dti
tm.assert_index_equal(res2, expected)

Expand All @@ -1657,13 +1672,15 @@ def test_dti_add_offset_index(self, tz_naive_fixture, names):
other = pd.Index([pd.offsets.MonthEnd(), pd.offsets.Day(n=2)],
name=names[1])

with tm.assert_produces_warning(PerformanceWarning):
with tm.assert_produces_warning(PerformanceWarning,
clear=[pd.core.arrays.datetimelike]):
res = dti + other
expected = DatetimeIndex([dti[n] + other[n] for n in range(len(dti))],
name=names[2], freq='infer')
tm.assert_index_equal(res, expected)

with tm.assert_produces_warning(PerformanceWarning):
with tm.assert_produces_warning(PerformanceWarning,
clear=[pd.core.arrays.datetimelike]):
res2 = other + dti
tm.assert_index_equal(res2, expected)

Expand All @@ -1673,7 +1690,8 @@ def test_dti_sub_offset_array(self, tz_naive_fixture):
dti = pd.date_range('2017-01-01', periods=2, tz=tz)
other = np.array([pd.offsets.MonthEnd(), pd.offsets.Day(n=2)])

with tm.assert_produces_warning(PerformanceWarning):
with tm.assert_produces_warning(PerformanceWarning,
clear=[pd.core.arrays.datetimelike]):
res = dti - other
expected = DatetimeIndex([dti[n] - other[n] for n in range(len(dti))],
name=dti.name, freq='infer')
Expand All @@ -1689,7 +1707,8 @@ def test_dti_sub_offset_index(self, tz_naive_fixture, names):
other = pd.Index([pd.offsets.MonthEnd(), pd.offsets.Day(n=2)],
name=names[1])

with tm.assert_produces_warning(PerformanceWarning):
with tm.assert_produces_warning(PerformanceWarning,
clear=[pd.core.arrays.datetimelike]):
res = dti - other
expected = DatetimeIndex([dti[n] - other[n] for n in range(len(dti))],
name=names[2], freq='infer')
Expand All @@ -1708,18 +1727,21 @@ def test_dti_with_offset_series(self, tz_naive_fixture, names):
expected_add = Series([dti[n] + other[n] for n in range(len(dti))],
name=names[2])

with tm.assert_produces_warning(PerformanceWarning):
with tm.assert_produces_warning(PerformanceWarning,
clear=[pd.core.arrays.datetimelike]):
res = dti + other
tm.assert_series_equal(res, expected_add)

with tm.assert_produces_warning(PerformanceWarning):
with tm.assert_produces_warning(PerformanceWarning,
clear=[pd.core.arrays.datetimelike]):
res2 = other + dti
tm.assert_series_equal(res2, expected_add)

expected_sub = Series([dti[n] - other[n] for n in range(len(dti))],
name=names[2])

with tm.assert_produces_warning(PerformanceWarning):
with tm.assert_produces_warning(PerformanceWarning,
clear=[pd.core.arrays.datetimelike]):
res3 = dti - other
tm.assert_series_equal(res3, expected_sub)

Expand Down Expand Up @@ -1755,7 +1777,8 @@ def test_dt64_with_offset_array(klass, assert_func):
# GH#10699
# array of offsets
box = Series if klass is Series else pd.Index
with tm.assert_produces_warning(PerformanceWarning):
with tm.assert_produces_warning(PerformanceWarning,
clear=[pd.core.arrays.datetimelike]):
s = klass([Timestamp('2000-1-1'), Timestamp('2000-2-1')])
result = s + box([pd.offsets.DateOffset(years=1),
pd.offsets.MonthEnd()])
Expand Down
Loading