Skip to content

Commit d5ff3f2

Browse files
plammensluckyvs1
authored andcommitted
DOC: Enhance asfreq docs (pandas-dev#36369)
1 parent c4ed492 commit d5ff3f2

File tree

9 files changed

+259
-84
lines changed

9 files changed

+259
-84
lines changed

pandas/core/arrays/period.py

+20-7
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,
@@ -51,6 +51,10 @@
5151
from pandas.core.arrays import datetimelike as dtl
5252
import pandas.core.common as com
5353

54+
_shared_doc_kwargs = {
55+
"klass": "PeriodArray",
56+
}
57+
5458

5559
def _field_accessor(name: str, docstring=None):
5660
def f(self):
@@ -67,8 +71,8 @@ class PeriodArray(PeriodMixin, dtl.DatelikeOps):
6771
"""
6872
Pandas ExtensionArray for storing Period data.
6973
70-
Users should use :func:`period_range` to create new instances.
71-
Alternatively, :func:`array` can be used to create new instances
74+
Users should use :func:`~pandas.period_array` to create new instances.
75+
Alternatively, :func:`~pandas.array` can be used to create new instances
7276
from a sequence of Period scalars.
7377
7478
Parameters
@@ -495,15 +499,19 @@ def _time_shift(self, periods, freq=None):
495499
def _box_func(self, x) -> Union[Period, NaTType]:
496500
return Period._from_ordinal(ordinal=x, freq=self.freq)
497501

502+
@doc(**_shared_doc_kwargs, other="PeriodIndex", other_name="PeriodIndex")
498503
def asfreq(self, freq=None, how: str = "E") -> "PeriodArray":
499504
"""
500-
Convert the Period Array/Index to the specified frequency `freq`.
505+
Convert the {klass} to the specified frequency `freq`.
506+
507+
Equivalent to applying :meth:`pandas.Period.asfreq` with the given arguments
508+
to each :class:`~pandas.Period` in this {klass}.
501509
502510
Parameters
503511
----------
504512
freq : str
505513
A frequency.
506-
how : str {'E', 'S'}
514+
how : str {{'E', 'S'}}, default 'E'
507515
Whether the elements should be aligned to the end
508516
or start within pa period.
509517
@@ -514,8 +522,13 @@ def asfreq(self, freq=None, how: str = "E") -> "PeriodArray":
514522
515523
Returns
516524
-------
517-
Period Array/Index
518-
Constructed with the new frequency.
525+
{klass}
526+
The transformed {klass} with the new frequency.
527+
528+
See Also
529+
--------
530+
{other}.asfreq: Convert each Period in a {other_name} to the given frequency.
531+
Period.asfreq : Convert a :class:`~pandas.Period` object to the given frequency.
519532
520533
Examples
521534
--------

pandas/core/frame.py

+51
Original file line numberDiff line numberDiff line change
@@ -167,7 +167,10 @@
167167
if TYPE_CHECKING:
168168
from typing import Literal
169169

170+
from pandas._typing import TimedeltaConvertibleTypes, TimestampConvertibleTypes
171+
170172
from pandas.core.groupby.generic import DataFrameGroupBy
173+
from pandas.core.resample import Resampler
171174

172175
from pandas.io.formats.style import Styler
173176

@@ -9350,6 +9353,54 @@ def quantile(
93509353

93519354
return result
93529355

9356+
@doc(NDFrame.asfreq, **_shared_doc_kwargs)
9357+
def asfreq(
9358+
self,
9359+
freq,
9360+
method=None,
9361+
how: Optional[str] = None,
9362+
normalize: bool = False,
9363+
fill_value=None,
9364+
) -> "DataFrame":
9365+
return super().asfreq(
9366+
freq=freq,
9367+
method=method,
9368+
how=how,
9369+
normalize=normalize,
9370+
fill_value=fill_value,
9371+
)
9372+
9373+
@doc(NDFrame.resample, **_shared_doc_kwargs)
9374+
def resample(
9375+
self,
9376+
rule,
9377+
axis=0,
9378+
closed: Optional[str] = None,
9379+
label: Optional[str] = None,
9380+
convention: str = "start",
9381+
kind: Optional[str] = None,
9382+
loffset=None,
9383+
base: Optional[int] = None,
9384+
on=None,
9385+
level=None,
9386+
origin: Union[str, "TimestampConvertibleTypes"] = "start_day",
9387+
offset: Optional["TimedeltaConvertibleTypes"] = None,
9388+
) -> "Resampler":
9389+
return super().resample(
9390+
rule=rule,
9391+
axis=axis,
9392+
closed=closed,
9393+
label=label,
9394+
convention=convention,
9395+
kind=kind,
9396+
loffset=loffset,
9397+
base=base,
9398+
on=on,
9399+
level=level,
9400+
origin=origin,
9401+
offset=offset,
9402+
)
9403+
93539404
def to_timestamp(
93549405
self, freq=None, how: str = "start", axis: Axis = 0, copy: bool = True
93559406
) -> DataFrame:

pandas/core/generic.py

+50-34
Original file line numberDiff line numberDiff line change
@@ -7713,7 +7713,7 @@ def clip(
77137713

77147714
return result
77157715

7716-
@final
7716+
@doc(**_shared_doc_kwargs)
77177717
def asfreq(
77187718
self: FrameOrSeries,
77197719
freq,
@@ -7723,26 +7723,39 @@ def asfreq(
77237723
fill_value=None,
77247724
) -> FrameOrSeries:
77257725
"""
7726-
Convert TimeSeries to specified frequency.
7727-
7728-
Optionally provide filling method to pad/backfill missing values.
7726+
Convert time series to specified frequency.
77297727
77307728
Returns the original data conformed to a new index with the specified
7731-
frequency. ``resample`` is more appropriate if an operation, such as
7732-
summarization, is necessary to represent the data at the new frequency.
7729+
frequency.
7730+
7731+
If the index of this {klass} is a :class:`~pandas.PeriodIndex`, the new index
7732+
is the result of transforming the original index with
7733+
:meth:`PeriodIndex.asfreq <pandas.PeriodIndex.asfreq>` (so the original index
7734+
will map one-to-one to the new index).
7735+
7736+
Otherwise, the new index will be equivalent to ``pd.date_range(start, end,
7737+
freq=freq)`` where ``start`` and ``end`` are, respectively, the first and
7738+
last entries in the original index (see :func:`pandas.date_range`). The
7739+
values corresponding to any timesteps in the new index which were not present
7740+
in the original index will be null (``NaN``), unless a method for filling
7741+
such unknowns is provided (see the ``method`` parameter below).
7742+
7743+
The :meth:`resample` method is more appropriate if an operation on each group of
7744+
timesteps (such as an aggregate) is necessary to represent the data at the new
7745+
frequency.
77337746
77347747
Parameters
77357748
----------
77367749
freq : DateOffset or str
77377750
Frequency DateOffset or string.
7738-
method : {'backfill'/'bfill', 'pad'/'ffill'}, default None
7751+
method : {{'backfill'/'bfill', 'pad'/'ffill'}}, default None
77397752
Method to use for filling holes in reindexed Series (note this
77407753
does not fill NaNs that already were present):
77417754
77427755
* 'pad' / 'ffill': propagate last valid observation forward to next
77437756
valid
77447757
* 'backfill' / 'bfill': use NEXT valid observation to fill.
7745-
how : {'start', 'end'}, default end
7758+
how : {{'start', 'end'}}, default end
77467759
For PeriodIndex only (see PeriodIndex.asfreq).
77477760
normalize : bool, default False
77487761
Whether to reset output index to midnight.
@@ -7752,8 +7765,8 @@ def asfreq(
77527765
77537766
Returns
77547767
-------
7755-
Same type as caller
7756-
Object converted to the specified frequency.
7768+
{klass}
7769+
{klass} object reindexed to the specified frequency.
77577770
77587771
See Also
77597772
--------
@@ -7770,7 +7783,7 @@ def asfreq(
77707783
77717784
>>> index = pd.date_range('1/1/2000', periods=4, freq='T')
77727785
>>> series = pd.Series([0.0, None, 2.0, 3.0], index=index)
7773-
>>> df = pd.DataFrame({'s':series})
7786+
>>> df = pd.DataFrame({{'s': series}})
77747787
>>> df
77757788
s
77767789
2000-01-01 00:00:00 0.0
@@ -7969,7 +7982,7 @@ def between_time(
79697982
)
79707983
return self._take_with_is_copy(indexer, axis=axis)
79717984

7972-
@final
7985+
@doc(**_shared_doc_kwargs)
79737986
def resample(
79747987
self,
79757988
rule,
@@ -7988,31 +8001,31 @@ def resample(
79888001
"""
79898002
Resample time-series data.
79908003
7991-
Convenience method for frequency conversion and resampling of time
7992-
series. Object must have a datetime-like index (`DatetimeIndex`,
7993-
`PeriodIndex`, or `TimedeltaIndex`), or pass datetime-like values
7994-
to the `on` or `level` keyword.
8004+
Convenience method for frequency conversion and resampling of time series.
8005+
The object must have a datetime-like index (`DatetimeIndex`, `PeriodIndex`,
8006+
or `TimedeltaIndex`), or the caller must pass the label of a datetime-like
8007+
series/index to the ``on``/``level`` keyword parameter.
79958008
79968009
Parameters
79978010
----------
79988011
rule : DateOffset, Timedelta or str
79998012
The offset string or object representing target conversion.
8000-
axis : {0 or 'index', 1 or 'columns'}, default 0
8013+
axis : {{0 or 'index', 1 or 'columns'}}, default 0
80018014
Which axis to use for up- or down-sampling. For `Series` this
80028015
will default to 0, i.e. along the rows. Must be
80038016
`DatetimeIndex`, `TimedeltaIndex` or `PeriodIndex`.
8004-
closed : {'right', 'left'}, default None
8017+
closed : {{'right', 'left'}}, default None
80058018
Which side of bin interval is closed. The default is 'left'
80068019
for all frequency offsets except for 'M', 'A', 'Q', 'BM',
80078020
'BA', 'BQ', and 'W' which all have a default of 'right'.
8008-
label : {'right', 'left'}, default None
8021+
label : {{'right', 'left'}}, default None
80098022
Which bin edge label to label bucket with. The default is 'left'
80108023
for all frequency offsets except for 'M', 'A', 'Q', 'BM',
80118024
'BA', 'BQ', and 'W' which all have a default of 'right'.
8012-
convention : {'start', 'end', 's', 'e'}, default 'start'
8025+
convention : {{'start', 'end', 's', 'e'}}, default 'start'
80138026
For `PeriodIndex` only, controls whether to use the start or
80148027
end of `rule`.
8015-
kind : {'timestamp', 'period'}, optional, default None
8028+
kind : {{'timestamp', 'period'}}, optional, default None
80168029
Pass 'timestamp' to convert the resulting index to a
80178030
`DateTimeIndex` or 'period' to convert it to a `PeriodIndex`.
80188031
By default the input representation is retained.
@@ -8037,7 +8050,7 @@ def resample(
80378050
level : str or int, optional
80388051
For a MultiIndex, level (name or number) to use for
80398052
resampling. `level` must be datetime-like.
8040-
origin : {'epoch', 'start', 'start_day'}, Timestamp or str, default 'start_day'
8053+
origin : {{'epoch','start','start_day'}}, Timestamp or str, default 'start_day'
80418054
The timestamp on which to adjust the grouping. The timezone of origin
80428055
must match the timezone of the index.
80438056
If a timestamp is not used, these values are also supported:
@@ -8055,13 +8068,15 @@ def resample(
80558068
80568069
Returns
80578070
-------
8058-
Resampler object
8071+
pandas.core.Resampler
8072+
:class:`~pandas.core.Resampler` object.
80598073
80608074
See Also
80618075
--------
8062-
groupby : Group by mapping, function, label, or list of labels.
80638076
Series.resample : Resample a Series.
8064-
DataFrame.resample: Resample a DataFrame.
8077+
DataFrame.resample : Resample a DataFrame.
8078+
groupby : Group {klass} by mapping, function, label, or list of labels.
8079+
asfreq : Reindex a {klass} with the given frequency without grouping.
80658080
80668081
Notes
80678082
-----
@@ -8220,8 +8235,8 @@ def resample(
82208235
For DataFrame objects, the keyword `on` can be used to specify the
82218236
column instead of the index for resampling.
82228237
8223-
>>> d = {'price': [10, 11, 9, 13, 14, 18, 17, 19],
8224-
... 'volume': [50, 60, 40, 100, 50, 100, 40, 50]}
8238+
>>> d = {{'price': [10, 11, 9, 13, 14, 18, 17, 19],
8239+
... 'volume': [50, 60, 40, 100, 50, 100, 40, 50]}}
82258240
>>> df = pd.DataFrame(d)
82268241
>>> df['week_starting'] = pd.date_range('01/01/2018',
82278242
... periods=8,
@@ -8246,13 +8261,14 @@ def resample(
82468261
specify on which level the resampling needs to take place.
82478262
82488263
>>> days = pd.date_range('1/1/2000', periods=4, freq='D')
8249-
>>> d2 = {'price': [10, 11, 9, 13, 14, 18, 17, 19],
8250-
... 'volume': [50, 60, 40, 100, 50, 100, 40, 50]}
8251-
>>> df2 = pd.DataFrame(d2,
8252-
... index=pd.MultiIndex.from_product([days,
8253-
... ['morning',
8254-
... 'afternoon']]
8255-
... ))
8264+
>>> d2 = {{'price': [10, 11, 9, 13, 14, 18, 17, 19],
8265+
... 'volume': [50, 60, 40, 100, 50, 100, 40, 50]}}
8266+
>>> df2 = pd.DataFrame(
8267+
... d2,
8268+
... index=pd.MultiIndex.from_product(
8269+
... [days, ['morning', 'afternoon']]
8270+
... )
8271+
... )
82568272
>>> df2
82578273
price volume
82588274
2000-01-01 morning 10 50

0 commit comments

Comments
 (0)