Skip to content

Commit 7e88123

Browse files
committed
DOC: enhance documentation for asfreq
1 parent 8df0218 commit 7e88123

File tree

6 files changed

+181
-38
lines changed

6 files changed

+181
-38
lines changed

pandas/core/arrays/period.py

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727
period_asfreq_arr,
2828
)
2929
from pandas._typing import AnyArrayLike
30-
from pandas.util._decorators import cache_readonly
30+
from pandas.util._decorators import cache_readonly, doc
3131

3232
from pandas.core.dtypes.common import (
3333
TD64NS_DTYPE,
@@ -50,6 +50,10 @@
5050
from pandas.core.arrays import datetimelike as dtl
5151
import pandas.core.common as com
5252

53+
_shared_doc_kwargs = {
54+
"klass": "PeriodArray",
55+
}
56+
5357

5458
def _field_accessor(name: str, docstring=None):
5559
def f(self):
@@ -489,15 +493,19 @@ def _time_shift(self, periods, freq=None):
489493
def _box_func(self, x) -> Union[Period, NaTType]:
490494
return Period._from_ordinal(ordinal=x, freq=self.freq)
491495

496+
@doc(**_shared_doc_kwargs, other="PeriodIndex", other_name="PeriodIndex")
492497
def asfreq(self, freq=None, how: str = "E") -> "PeriodArray":
493498
"""
494-
Convert the Period Array/Index to the specified frequency `freq`.
499+
Convert the {klass} to the specified frequency `freq`.
500+
501+
Equivalent to applying :meth:`pandas.Period.asfreq` with the given arguments
502+
to each :class:`~pandas.Period` in this {klass}.
495503
496504
Parameters
497505
----------
498506
freq : str
499507
A frequency.
500-
how : str {'E', 'S'}
508+
how : str {{'E', 'S'}}, default 'E'
501509
Whether the elements should be aligned to the end
502510
or start within pa period.
503511
@@ -508,8 +516,13 @@ def asfreq(self, freq=None, how: str = "E") -> "PeriodArray":
508516
509517
Returns
510518
-------
511-
Period Array/Index
512-
Constructed with the new frequency.
519+
{klass}
520+
The transformed {klass} with the new frequency.
521+
522+
See Also
523+
--------
524+
{other}.asfreq: Convert each Period in a {other_name} to the given frequency.
525+
Period.asfreq : Convert a :class:`~pandas.Period` object to the given frequency.
513526
514527
Examples
515528
--------

pandas/core/frame.py

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,10 @@
151151
import pandas.plotting
152152

153153
if TYPE_CHECKING:
154+
from pandas._typing import TimedeltaConvertibleTypes, TimestampConvertibleTypes
155+
154156
from pandas.core.groupby.generic import DataFrameGroupBy
157+
from pandas.core.resample import Resampler
155158

156159
from pandas.io.formats.style import Styler
157160

@@ -9104,6 +9107,54 @@ def quantile(self, q=0.5, axis=0, numeric_only=True, interpolation="linear"):
91049107

91059108
return result
91069109

9110+
@doc(NDFrame.asfreq, **_shared_doc_kwargs)
9111+
def asfreq(
9112+
self,
9113+
freq,
9114+
method=None,
9115+
how: Optional[str] = None,
9116+
normalize: bool = False,
9117+
fill_value=None,
9118+
) -> "DataFrame":
9119+
return super().asfreq(
9120+
freq=freq,
9121+
method=method,
9122+
how=how,
9123+
normalize=normalize,
9124+
fill_value=fill_value,
9125+
)
9126+
9127+
@doc(NDFrame.resample, **_shared_doc_kwargs)
9128+
def resample(
9129+
self,
9130+
rule,
9131+
axis=0,
9132+
closed: Optional[str] = None,
9133+
label: Optional[str] = None,
9134+
convention: str = "start",
9135+
kind: Optional[str] = None,
9136+
loffset=None,
9137+
base: Optional[int] = None,
9138+
on=None,
9139+
level=None,
9140+
origin: Union[str, "TimestampConvertibleTypes"] = "start_day",
9141+
offset: Optional["TimedeltaConvertibleTypes"] = None,
9142+
) -> "Resampler":
9143+
return super().resample(
9144+
rule=rule,
9145+
axis=axis,
9146+
closed=closed,
9147+
label=label,
9148+
convention=convention,
9149+
kind=kind,
9150+
loffset=loffset,
9151+
base=base,
9152+
on=on,
9153+
level=level,
9154+
origin=origin,
9155+
offset=offset,
9156+
)
9157+
91079158
def to_timestamp(
91089159
self, freq=None, how: str = "start", axis: Axis = 0, copy: bool = True
91099160
) -> DataFrame:

pandas/core/generic.py

Lines changed: 50 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -7518,6 +7518,7 @@ def clip(
75187518

75197519
return result
75207520

7521+
@doc(**_shared_doc_kwargs)
75217522
def asfreq(
75227523
self: FrameOrSeries,
75237524
freq,
@@ -7527,26 +7528,39 @@ def asfreq(
75277528
fill_value=None,
75287529
) -> FrameOrSeries:
75297530
"""
7530-
Convert TimeSeries to specified frequency.
7531-
7532-
Optionally provide filling method to pad/backfill missing values.
7531+
Convert time series to specified frequency.
75337532
75347533
Returns the original data conformed to a new index with the specified
7535-
frequency. ``resample`` is more appropriate if an operation, such as
7536-
summarization, is necessary to represent the data at the new frequency.
7534+
frequency.
7535+
7536+
If the index of this {klass} is a :class:`~pandas.PeriodIndex`, the new index
7537+
is the result of transforming the original index with
7538+
:meth:`PeriodIndex.asfreq pandas.PeriodIndex.asfreq` (so the original index
7539+
will map one-to-one to the new index).
7540+
7541+
Otherwise, the new index will be equivalent to ``pd.date_range(start, end,
7542+
freq=freq)`` where ``start`` and ``end`` are, respectively, the first and
7543+
last entries in the original index. (see :func:`pandas.date_range`). The
7544+
values corresponding to any timesteps in the new index which were not present
7545+
in the original index will be null (``NaN``), unless a method for filling
7546+
such unknowns is provided (see the ``method`` parameter below).
7547+
7548+
The :meth:`resample` method is more appropriate if an operation on each group of
7549+
timesteps (such as an aggregate) is necessary to represent the data at the new
7550+
frequency.
75377551
75387552
Parameters
75397553
----------
75407554
freq : DateOffset or str
75417555
Frequency DateOffset or string.
7542-
method : {'backfill'/'bfill', 'pad'/'ffill'}, default None
7556+
method : {{'backfill'/'bfill', 'pad'/'ffill'}}, default None
75437557
Method to use for filling holes in reindexed Series (note this
75447558
does not fill NaNs that already were present):
75457559
75467560
* 'pad' / 'ffill': propagate last valid observation forward to next
75477561
valid
75487562
* 'backfill' / 'bfill': use NEXT valid observation to fill.
7549-
how : {'start', 'end'}, default end
7563+
how : {{'start', 'end'}}, default end
75507564
For PeriodIndex only (see PeriodIndex.asfreq).
75517565
normalize : bool, default False
75527566
Whether to reset output index to midnight.
@@ -7556,8 +7570,8 @@ def asfreq(
75567570
75577571
Returns
75587572
-------
7559-
Same type as caller
7560-
Object converted to the specified frequency.
7573+
{klass}
7574+
{klass} object reindexed to the specified frequency.
75617575
75627576
See Also
75637577
--------
@@ -7574,7 +7588,7 @@ def asfreq(
75747588
75757589
>>> index = pd.date_range('1/1/2000', periods=4, freq='T')
75767590
>>> series = pd.Series([0.0, None, 2.0, 3.0], index=index)
7577-
>>> df = pd.DataFrame({'s':series})
7591+
>>> df = pd.DataFrame({{'s':series}})
75787592
>>> df
75797593
s
75807594
2000-01-01 00:00:00 0.0
@@ -7771,6 +7785,7 @@ def between_time(
77717785
)
77727786
return self._take_with_is_copy(indexer, axis=axis)
77737787

7788+
@doc(**_shared_doc_kwargs)
77747789
def resample(
77757790
self,
77767791
rule,
@@ -7789,31 +7804,31 @@ def resample(
77897804
"""
77907805
Resample time-series data.
77917806
7792-
Convenience method for frequency conversion and resampling of time
7793-
series. Object must have a datetime-like index (`DatetimeIndex`,
7794-
`PeriodIndex`, or `TimedeltaIndex`), or pass datetime-like values
7795-
to the `on` or `level` keyword.
7807+
Convenience method for frequency conversion and resampling of time series.
7808+
The object must have a datetime-like index (`DatetimeIndex`, `PeriodIndex`,
7809+
or `TimedeltaIndex`), or the caller must pass the label of a datetime-like
7810+
series/index to the ``on``/``level`` keyword parameter.
77967811
77977812
Parameters
77987813
----------
77997814
rule : DateOffset, Timedelta or str
78007815
The offset string or object representing target conversion.
7801-
axis : {0 or 'index', 1 or 'columns'}, default 0
7816+
axis : {{0 or 'index', 1 or 'columns'}}, default 0
78027817
Which axis to use for up- or down-sampling. For `Series` this
78037818
will default to 0, i.e. along the rows. Must be
78047819
`DatetimeIndex`, `TimedeltaIndex` or `PeriodIndex`.
7805-
closed : {'right', 'left'}, default None
7820+
closed : {{'right', 'left'}}, default None
78067821
Which side of bin interval is closed. The default is 'left'
78077822
for all frequency offsets except for 'M', 'A', 'Q', 'BM',
78087823
'BA', 'BQ', and 'W' which all have a default of 'right'.
7809-
label : {'right', 'left'}, default None
7824+
label : {{'right', 'left'}}, default None
78107825
Which bin edge label to label bucket with. The default is 'left'
78117826
for all frequency offsets except for 'M', 'A', 'Q', 'BM',
78127827
'BA', 'BQ', and 'W' which all have a default of 'right'.
7813-
convention : {'start', 'end', 's', 'e'}, default 'start'
7828+
convention : {{'start', 'end', 's', 'e'}}, default 'start'
78147829
For `PeriodIndex` only, controls whether to use the start or
78157830
end of `rule`.
7816-
kind : {'timestamp', 'period'}, optional, default None
7831+
kind : {{'timestamp', 'period'}}, optional, default None
78177832
Pass 'timestamp' to convert the resulting index to a
78187833
`DateTimeIndex` or 'period' to convert it to a `PeriodIndex`.
78197834
By default the input representation is retained.
@@ -7838,7 +7853,7 @@ def resample(
78387853
level : str or int, optional
78397854
For a MultiIndex, level (name or number) to use for
78407855
resampling. `level` must be datetime-like.
7841-
origin : {'epoch', 'start', 'start_day'}, Timestamp or str, default 'start_day'
7856+
origin : {{'epoch','start','start_day'}}, Timestamp or str, default 'start_day'
78427857
The timestamp on which to adjust the grouping. The timezone of origin
78437858
must match the timezone of the index.
78447859
If a timestamp is not used, these values are also supported:
@@ -7856,13 +7871,15 @@ def resample(
78567871
78577872
Returns
78587873
-------
7859-
Resampler object
7874+
pandas.core.Resampler
7875+
:class:`~pandas.core.Resampler` object.
78607876
78617877
See Also
78627878
--------
7863-
groupby : Group by mapping, function, label, or list of labels.
78647879
Series.resample : Resample a Series.
7865-
DataFrame.resample: Resample a DataFrame.
7880+
DataFrame.resample : Resample a DataFrame.
7881+
groupby : Group {klass} by mapping, function, label, or list of labels.
7882+
asfreq : Reindex a {klass} with the given frequency without grouping.
78667883
78677884
Notes
78687885
-----
@@ -8021,8 +8038,8 @@ def resample(
80218038
For DataFrame objects, the keyword `on` can be used to specify the
80228039
column instead of the index for resampling.
80238040
8024-
>>> d = dict({'price': [10, 11, 9, 13, 14, 18, 17, 19],
8025-
... 'volume': [50, 60, 40, 100, 50, 100, 40, 50]})
8041+
>>> d = {{'price': [10, 11, 9, 13, 14, 18, 17, 19],
8042+
... 'volume': [50, 60, 40, 100, 50, 100, 40, 50]}}
80268043
>>> df = pd.DataFrame(d)
80278044
>>> df['week_starting'] = pd.date_range('01/01/2018',
80288045
... periods=8,
@@ -8047,13 +8064,14 @@ def resample(
80478064
specify on which level the resampling needs to take place.
80488065
80498066
>>> days = pd.date_range('1/1/2000', periods=4, freq='D')
8050-
>>> d2 = dict({'price': [10, 11, 9, 13, 14, 18, 17, 19],
8051-
... 'volume': [50, 60, 40, 100, 50, 100, 40, 50]})
8052-
>>> df2 = pd.DataFrame(d2,
8053-
... index=pd.MultiIndex.from_product([days,
8054-
... ['morning',
8055-
... 'afternoon']]
8056-
... ))
8067+
>>> d2 = {{'price': [10, 11, 9, 13, 14, 18, 17, 19],
8068+
... 'volume': [50, 60, 40, 100, 50, 100, 40, 50]}}
8069+
>>> df2 = pd.DataFrame(
8070+
... d2,
8071+
... index=pd.MultiIndex.from_product(
8072+
... [days, ['morning', 'afternoon']]
8073+
... )
8074+
... )
80578075
>>> df2
80588076
price volume
80598077
2000-01-01 morning 10 50

pandas/core/indexes/period.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,9 @@
4444

4545
_index_doc_kwargs = dict(ibase._index_doc_kwargs)
4646
_index_doc_kwargs.update(dict(target_klass="PeriodIndex or list of Periods"))
47+
_shared_doc_kwargs = {
48+
"klass": "PeriodArray",
49+
}
4750

4851
# --- Period index sketch
4952

@@ -150,7 +153,12 @@ class PeriodIndex(DatetimeIndexOpsMixin, Int64Index):
150153
# --------------------------------------------------------------------
151154
# methods that dispatch to array and wrap result in PeriodIndex
152155

153-
@doc(PeriodArray.asfreq)
156+
@doc(
157+
PeriodArray.asfreq,
158+
other="pandas.arrays.PeriodArray",
159+
other_name="PeriodArray",
160+
**_shared_doc_kwargs,
161+
)
154162
def asfreq(self, freq=None, how: str = "E") -> "PeriodIndex":
155163
arr = self._data.asfreq(freq, how)
156164
return type(self)._simple_new(arr, name=self.name)

pandas/core/resample.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1862,6 +1862,8 @@ def _adjust_dates_anchored(
18621862
def asfreq(obj, freq, method=None, how=None, normalize=False, fill_value=None):
18631863
"""
18641864
Utility frequency conversion method for Series/DataFrame.
1865+
1866+
See :meth:`pandas.NDFrame.asfreq` for full documentation.
18651867
"""
18661868
if isinstance(obj.index, PeriodIndex):
18671869
if method is not None:

0 commit comments

Comments
 (0)