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 week, weekofyear in Series.dt,DatetimeIndex #33595

Merged
merged 15 commits into from
May 26, 2020
Merged
Show file tree
Hide file tree
Changes from all 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
3 changes: 3 additions & 0 deletions doc/source/whatsnew/v1.1.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -590,6 +590,9 @@ Deprecations

- :func:`pandas.api.types.is_categorical` is deprecated and will be removed in a future version; use `:func:pandas.api.types.is_categorical_dtype` instead (:issue:`33385`)
- :meth:`Index.get_value` is deprecated and will be removed in a future version (:issue:`19728`)
- :meth:`Series.dt.week` and `Series.dt.weekofyear` are deprecated and will be removed in a future version, use :meth:`Series.dt.isocalendar().week` instead (:issue:`33595`)
- :meth:`DatetimeIndex.week` and `DatetimeIndex.weekofyear` are deprecated and will be removed in a future version, use :meth:`DatetimeIndex.isocalendar().week` instead (:issue:`33595`)
- :meth:`DatetimeArray.week` and `DatetimeArray.weekofyear` are deprecated and will be removed in a future version, use :meth:`DatetimeArray.isocalendar().week` instead (:issue:`33595`)
- :meth:`DateOffset.__call__` is deprecated and will be removed in a future version, use ``offset + other`` instead (:issue:`34171`)
- Indexing an :class:`Index` object with a float key is deprecated, and will
raise an ``IndexError`` in the future. You can manually convert to an integer key
Expand Down
34 changes: 26 additions & 8 deletions pandas/core/arrays/datetimes.py
Original file line number Diff line number Diff line change
Expand Up @@ -1298,6 +1298,32 @@ def isocalendar(self):
iso_calendar_df.iloc[self._isnan] = None
return iso_calendar_df

@property
def weekofyear(self):
"""
The week ordinal of the year.

.. deprecated:: 1.1.0

weekofyear and week have been deprecated.
Please use DatetimeIndex.isocalendar().week instead.
"""
warnings.warn(
"weekofyear and week have been deprecated, please use "
"DatetimeIndex.isocalendar().week instead, which returns "
"a Series. To exactly reproduce the behavior of week and "
"weekofyear and return an Index, you may call "
"pd.Int64Index(idx.isocalendar().week)",
FutureWarning,
stacklevel=3,
)
week_series = self.isocalendar().week
if week_series.hasnans:
return week_series.to_numpy(dtype="float64", na_value=np.nan)
return week_series.to_numpy(dtype="int64")

week = weekofyear

year = _field_accessor(
"year",
"Y",
Expand Down Expand Up @@ -1482,14 +1508,6 @@ def isocalendar(self):
dtype: int64
""",
)
weekofyear = _field_accessor(
"weekofyear",
"woy",
"""
The week ordinal of the year.
""",
)
week = weekofyear
_dayofweek_doc = """
The day of the week with Monday=0, Sunday=6.

Expand Down
25 changes: 25 additions & 0 deletions pandas/core/indexes/accessors.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
datetimelike delegation
"""
from typing import TYPE_CHECKING
import warnings

import numpy as np

Expand Down Expand Up @@ -250,6 +251,30 @@ def isocalendar(self):
"""
return self._get_values().isocalendar().set_index(self._parent.index)

@property
def weekofyear(self):
"""
The week ordinal of the year.

.. deprecated:: 1.1.0

Series.dt.weekofyear and Series.dt.week have been deprecated.
Please use Series.dt.isocalendar().week instead.
"""
warnings.warn(
"Series.dt.weekofyear and Series.dt.week have been deprecated. "
"Please use Series.dt.isocalendar().week instead.",
FutureWarning,
stacklevel=2,
)
week_series = self.isocalendar().week
week_series.name = self.name
if week_series.hasnans:
Copy link
Contributor

Choose a reason for hiding this comment

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

we do it like this now?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yes, in the current week accessor the array is converted to a float and masked if there are nans. This reproduces that behavior instead of passing back a UInt32 series.

return week_series.astype("float64")
return week_series.astype("int64")

week = weekofyear


@delegate_names(
delegate=TimedeltaArray, accessors=TimedeltaArray._datetimelike_ops, typ="property"
Expand Down
3 changes: 3 additions & 0 deletions pandas/tests/arrays/test_datetimelike.py
Original file line number Diff line number Diff line change
Expand Up @@ -546,6 +546,9 @@ def test_bool_properties(self, datetime_index, propname):

@pytest.mark.parametrize("propname", pd.DatetimeIndex._field_ops)
def test_int_properties(self, datetime_index, propname):
if propname in ["week", "weekofyear"]:
# GH#33595 Deprecate week and weekofyear
return
dti = datetime_index
arr = DatetimeArray(dti)

Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/groupby/transform/test_transform.py
Original file line number Diff line number Diff line change
Expand Up @@ -1022,7 +1022,7 @@ def test_groupby_transform_with_datetimes(func, values):
dates = pd.date_range("1/1/2011", periods=10, freq="D")

stocks = pd.DataFrame({"price": np.arange(10.0)}, index=dates)
stocks["week_id"] = pd.to_datetime(stocks.index).week
stocks["week_id"] = dates.isocalendar().set_index(dates).week

result = stocks.groupby(stocks["week_id"])["price"].transform(func)

Expand Down
20 changes: 16 additions & 4 deletions pandas/tests/indexes/datetimes/test_misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,8 +156,8 @@ def test_datetimeindex_accessors(self):
assert dti.dayofyear[0] == 1
assert dti.dayofyear[120] == 121

assert dti.weekofyear[0] == 1
assert dti.weekofyear[120] == 18
assert dti.isocalendar().week[0] == 1
assert dti.isocalendar().week[120] == 18

assert dti.quarter[0] == 1
assert dti.quarter[120] == 2
Expand Down Expand Up @@ -192,7 +192,7 @@ def test_datetimeindex_accessors(self):
assert len(dti.microsecond) == 365
assert len(dti.dayofweek) == 365
assert len(dti.dayofyear) == 365
assert len(dti.weekofyear) == 365
assert len(dti.isocalendar()) == 365
assert len(dti.quarter) == 365
assert len(dti.is_month_start) == 365
assert len(dti.is_month_end) == 365
Expand All @@ -205,6 +205,9 @@ def test_datetimeindex_accessors(self):

# non boolean accessors -> return Index
for accessor in DatetimeIndex._field_ops:
if accessor in ["week", "weekofyear"]:
# GH#33595 Deprecate week and weekofyear
continue
res = getattr(dti, accessor)
assert len(res) == 365
assert isinstance(res, Index)
Expand Down Expand Up @@ -285,7 +288,7 @@ def test_datetimeindex_accessors(self):
dates = ["2013/12/29", "2013/12/30", "2013/12/31"]
dates = DatetimeIndex(dates, tz="Europe/Brussels")
expected = [52, 1, 1]
assert dates.weekofyear.tolist() == expected
assert dates.isocalendar().week.tolist() == expected
assert [d.weekofyear for d in dates] == expected

# GH 12806
Expand Down Expand Up @@ -383,6 +386,15 @@ def test_iter_readonly():
list(dti)


def test_week_and_weekofyear_are_deprecated():
# GH#33595 Deprecate week and weekofyear
idx = pd.date_range(start="2019-12-29", freq="D", periods=4)
Copy link
Contributor

Choose a reason for hiding this comment

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

same

with tm.assert_produces_warning(FutureWarning):
idx.week
with tm.assert_produces_warning(FutureWarning):
idx.weekofyear


def test_isocalendar_returns_correct_values_close_to_new_year_with_tz():
# GH 6538: Check that DatetimeIndex and its TimeStamp elements
# return the same weekofyear accessor close to new year w/ tz
Expand Down
8 changes: 6 additions & 2 deletions pandas/tests/indexes/datetimes/test_scalar_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,6 @@ def test_dti_date_out_of_range(self, data):
[
"dayofweek",
"dayofyear",
"week",
"weekofyear",
"quarter",
"days_in_month",
"is_month_start",
Expand All @@ -59,6 +57,12 @@ def test_dti_timestamp_fields(self, field):
result = getattr(Timestamp(idx[-1]), field)
assert result == expected

def test_dti_timestamp_isocalendar_fields(self):
idx = tm.makeDateIndex(100)
expected = tuple(idx.isocalendar().iloc[-1].to_list())
result = idx[-1].isocalendar()
assert result == expected

def test_dti_timestamp_freq_fields(self):
# extra fields from DatetimeIndex like quarter and week
idx = tm.makeDateIndex(100)
Expand Down
6 changes: 6 additions & 0 deletions pandas/tests/scalar/test_nat.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,9 @@ def test_nat_vector_field_access():
# on NaT/Timestamp for compat with datetime
if field == "weekday":
continue
if field in ["week", "weekofyear"]:
Copy link
Contributor

Choose a reason for hiding this comment

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

we should properly parameterize these tests (if you would like to make an issue would be great), PR even better :->

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Im happy to make another PR, will wait until this is merged.

# GH#33595 Deprecate week and weekofyear
continue

result = getattr(idx, field)
expected = Index([getattr(x, field) for x in idx])
Expand All @@ -78,6 +81,9 @@ def test_nat_vector_field_access():
# on NaT/Timestamp for compat with datetime
if field == "weekday":
continue
if field in ["week", "weekofyear"]:
# GH#33595 Deprecate week and weekofyear
continue

result = getattr(ser.dt, field)
expected = [getattr(x, field) for x in idx]
Expand Down
3 changes: 3 additions & 0 deletions pandas/tests/series/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -719,6 +719,9 @@ def test_dt_accessor_api_for_categorical(self):
tm.assert_equal(res, exp)

for attr in attr_names:
if attr in ["week", "weekofyear"]:
# GH#33595 Deprecate week and weekofyear
continue
res = getattr(c.dt, attr)
exp = getattr(s.dt, attr)

Expand Down
15 changes: 13 additions & 2 deletions pandas/tests/series/test_datetime_values.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,8 @@ def compare(s, name):
for s in cases:
for prop in ok_for_dt:
# we test freq below
if prop != "freq":
# we ignore week and weekofyear because they are deprecated
if prop not in ["freq", "week", "weekofyear"]:
compare(s, prop)

for prop in ok_for_dt_methods:
Expand Down Expand Up @@ -122,7 +123,8 @@ def compare(s, name):
for prop in ok_for_dt:

# we test freq below
if prop != "freq":
# we ignore week and weekofyear because they are deprecated
if prop not in ["freq", "week", "weekofyear"]:
compare(s, prop)

for prop in ok_for_dt_methods:
Expand Down Expand Up @@ -687,3 +689,12 @@ def test_isocalendar(self, input_series, expected_output):
expected_output, columns=["year", "week", "day"], dtype="UInt32"
)
tm.assert_frame_equal(result, expected_frame)


def test_week_and_weekofyear_are_deprecated():
# GH#33595 Deprecate week and weekofyear
series = pd.to_datetime(pd.Series(["2020-01-01"]))
Copy link
Contributor

Choose a reason for hiding this comment

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

same

with tm.assert_produces_warning(FutureWarning):
series.dt.week
with tm.assert_produces_warning(FutureWarning):
series.dt.weekofyear