From 866347aa786fcff5aae8b2777619d96cd7a5fa2e Mon Sep 17 00:00:00 2001 From: Matthew Roeschke Date: Wed, 27 Jul 2022 16:51:11 -0700 Subject: [PATCH 1/7] DOC: Add numpydoc SS06 validation --- ci/code_checks.sh | 4 +- pandas/_config/config.py | 5 +- pandas/_libs/interval.pyx | 5 +- pandas/_libs/lib.pyx | 3 +- pandas/_libs/tslibs/np_datetime.pyx | 8 +-- pandas/_libs/tslibs/offsets.pyx | 23 +++--- pandas/_libs/tslibs/period.pyx | 12 ++-- pandas/_libs/tslibs/timedeltas.pyx | 3 +- pandas/_libs/tslibs/timestamps.pyx | 31 ++++----- pandas/core/arrays/datetimelike.py | 6 +- pandas/core/arrays/datetimes.py | 21 +++--- pandas/core/arrays/interval.py | 32 ++++----- pandas/core/arrays/timedeltas.py | 9 +-- pandas/core/base.py | 9 +-- pandas/core/frame.py | 5 +- pandas/core/generic.py | 5 +- pandas/core/groupby/groupby.py | 8 +-- pandas/core/indexers/objects.py | 3 +- pandas/core/indexes/base.py | 24 +++---- pandas/core/indexes/datetimes.py | 14 ++-- pandas/core/indexes/multi.py | 6 +- pandas/core/indexes/numeric.py | 14 ++-- pandas/core/indexes/timedeltas.py | 8 +-- pandas/core/resample.py | 5 +- pandas/core/reshape/concat.py | 5 +- pandas/core/reshape/pivot.py | 7 +- pandas/core/series.py | 2 + pandas/core/strings/accessor.py | 5 +- pandas/errors/__init__.py | 104 +++++++++++++++------------- pandas/io/formats/style.py | 6 +- pandas/io/formats/style_render.py | 6 ++ pandas/io/pytables.py | 5 +- pandas/io/stata.py | 6 +- pandas/plotting/_misc.py | 10 +-- 34 files changed, 211 insertions(+), 208 deletions(-) diff --git a/ci/code_checks.sh b/ci/code_checks.sh index b42ffc66f7714..113186c746157 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -78,8 +78,8 @@ fi ### DOCSTRINGS ### if [[ -z "$CHECK" || "$CHECK" == "docstrings" ]]; then - MSG='Validate docstrings (EX04, GL01, GL02, GL03, GL04, GL05, GL06, GL07, GL09, GL10, PR03, PR04, PR05, PR06, PR08, PR09, PR10, RT01, RT04, RT05, SA02, SA03, SA04, SS01, SS02, SS03, SS04, SS05)' ; echo $MSG - $BASE_DIR/scripts/validate_docstrings.py --format=actions --errors=EX04,GL01,GL02,GL03,GL04,GL05,GL06,GL07,GL09,GL10,PR03,PR04,PR05,PR06,PR08,PR09,PR10,RT01,RT04,RT05,SA02,SA03,SA04,SS01,SS02,SS03,SS04,SS05 + MSG='Validate docstrings (EX04, GL01, GL02, GL03, GL04, GL05, GL06, GL07, GL09, GL10, PR03, PR04, PR05, PR06, PR08, PR09, PR10, RT01, RT04, RT05, SA02, SA03, SA04, SS01, SS02, SS03, SS04, SS05, SS06)' ; echo $MSG + $BASE_DIR/scripts/validate_docstrings.py --format=actions --errors=EX04,GL01,GL02,GL03,GL04,GL05,GL06,GL07,GL09,GL10,PR03,PR04,PR05,PR06,PR08,PR09,PR10,RT01,RT04,RT05,SA02,SA03,SA04,SS01,SS02,SS03,SS04,SS05,SS06 RET=$(($RET + $?)) ; echo $MSG "DONE" fi diff --git a/pandas/_config/config.py b/pandas/_config/config.py index eacbf1b016432..d5e77d824340d 100644 --- a/pandas/_config/config.py +++ b/pandas/_config/config.py @@ -102,8 +102,9 @@ class RegisteredOption(NamedTuple): class OptionError(AttributeError, KeyError): """ - Exception for pandas.options, backwards compatible with KeyError - checks. + Exception raised for pandas.options. + + Backwards compatible with KeyError checks. """ diff --git a/pandas/_libs/interval.pyx b/pandas/_libs/interval.pyx index bc0a63c5c5a33..33b96aedde443 100644 --- a/pandas/_libs/interval.pyx +++ b/pandas/_libs/interval.pyx @@ -384,10 +384,11 @@ cdef class Interval(IntervalMixin): @property def closed(self): """ - Whether the interval is closed on the left-side, right-side, both or - neither. + String describing the inclusive side the intervals. .. deprecated:: 1.5.0 + + Either ``left``, ``right``, ``both`` or ``neither`. """ warnings.warn( "Attribute `closed` is deprecated in favor of `inclusive`.", diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx index e353d224708b7..c90c9003c8d60 100644 --- a/pandas/_libs/lib.pyx +++ b/pandas/_libs/lib.pyx @@ -1347,8 +1347,7 @@ cdef object _try_infer_map(object dtype): def infer_dtype(value: object, skipna: bool = True) -> str: """ - Efficiently infer the type of a passed val, or list-like - array of values. Return a string describing the type. + Return a string label of the type of a scalar or list-like of values. Parameters ---------- diff --git a/pandas/_libs/tslibs/np_datetime.pyx b/pandas/_libs/tslibs/np_datetime.pyx index 8ab0ba24f9151..c58a8d4dc4ba6 100644 --- a/pandas/_libs/tslibs/np_datetime.pyx +++ b/pandas/_libs/tslibs/np_datetime.pyx @@ -156,16 +156,16 @@ cdef inline bint cmp_scalar(int64_t lhs, int64_t rhs, int op) except -1: class OutOfBoundsDatetime(ValueError): """ - Raised when the datetime is outside the range that - can be represented. + Raised when the datetime is outside the range that can be represented. """ pass class OutOfBoundsTimedelta(ValueError): """ - Raised when encountering a timedelta value that cannot be represented - as a timedelta64[ns]. + Raised when encountering a timedelta value that cannot be represented. + + Representation should be within a timedelta64[ns]. """ # Timedelta analogue to OutOfBoundsDatetime pass diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index 5f4f6b998a60a..48104965ec42b 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -585,9 +585,7 @@ cdef class BaseOffset: def apply_index(self, dtindex): """ - Vectorized apply of DateOffset to DatetimeIndex, - raises NotImplementedError for offsets without a - vectorized implementation. + Vectorized apply of DateOffset to DatetimeIndex. .. deprecated:: 1.1.0 @@ -2448,8 +2446,7 @@ cdef class SemiMonthOffset(SingleConstructorOffset): cdef class SemiMonthEnd(SemiMonthOffset): """ - Two DateOffset's per month repeating on the last - day of the month and day_of_month. + Two DateOffset's per month repeating on the last day of the month & day_of_month. Parameters ---------- @@ -2470,8 +2467,7 @@ cdef class SemiMonthEnd(SemiMonthOffset): cdef class SemiMonthBegin(SemiMonthOffset): """ - Two DateOffset's per month repeating on the first - day of the month and day_of_month. + Two DateOffset's per month repeating on the first day of the month & day_of_month. Parameters ---------- @@ -2704,8 +2700,9 @@ cdef class WeekOfMonth(WeekOfMonthMixin): cdef class LastWeekOfMonth(WeekOfMonthMixin): """ - Describes monthly dates in last week of month like "the last Tuesday of - each month". + Describes monthly dates in last week of month. + + For example "the last Tuesday of each month". Parameters ---------- @@ -2991,8 +2988,9 @@ cdef class FY5253(FY5253Mixin): cdef class FY5253Quarter(FY5253Mixin): """ - DateOffset increments between business quarter dates - for 52-53 week fiscal year (also known as a 4-4-5 calendar). + DateOffset increments between business quarter dates for 52-53 week fiscal year. + + Also known as a 4-4-5 calendar. It is used by companies that desire that their fiscal year always end on the same day of the week. @@ -3602,8 +3600,7 @@ def _get_offset(name: str) -> BaseOffset: cpdef to_offset(freq): """ - Return DateOffset object from string or tuple representation - or datetime.timedelta object. + Return DateOffset object from string or datetime.timedelta object. Parameters ---------- diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx index 3332628627739..3acaa024f52c2 100644 --- a/pandas/_libs/tslibs/period.pyx +++ b/pandas/_libs/tslibs/period.pyx @@ -2322,12 +2322,12 @@ cdef class _Period(PeriodMixin): def strftime(self, fmt: str) -> str: r""" - Returns the string representation of the :class:`Period`, depending - on the selected ``fmt``. ``fmt`` must be a string - containing one or several directives. The method recognizes the same - directives as the :func:`time.strftime` function of the standard Python - distribution, as well as the specific additional directives ``%f``, - ``%F``, ``%q``, ``%l``, ``%u``, ``%n``. + Returns a formatted string representation of the :class:`Period`. + + ``fmt`` must be a string containing one or several directives. + The method recognizes the same directives as the :func:`time.strftime` + function of the standard Python distribution, as well as the specific + additional directives ``%f``, ``%F``, ``%q``, ``%l``, ``%u``, ``%n``. (formatting & docs originally from scikits.timeries). +-----------+--------------------------------+-------+ diff --git a/pandas/_libs/tslibs/timedeltas.pyx b/pandas/_libs/tslibs/timedeltas.pyx index 39458c10ad35b..215d1c9d6c722 100644 --- a/pandas/_libs/tslibs/timedeltas.pyx +++ b/pandas/_libs/tslibs/timedeltas.pyx @@ -1464,7 +1464,8 @@ cdef class _Timedelta(timedelta): def isoformat(self) -> str: """ - Format Timedelta as ISO 8601 Duration like + Format the Timedelta as ISO 8601 Duration. + ``P[n]Y[n]M[n]DT[n]H[n]M[n]S``, where the ``[n]`` s are replaced by the values. See https://en.wikipedia.org/wiki/ISO_8601#Durations. diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx index dc4da6c9bf4d2..66d848ba43da9 100644 --- a/pandas/_libs/tslibs/timestamps.pyx +++ b/pandas/_libs/tslibs/timestamps.pyx @@ -1345,10 +1345,7 @@ class Timestamp(_Timestamp): @classmethod def fromordinal(cls, ordinal, freq=None, tz=None): """ - Timestamp.fromordinal(ordinal, freq=None, tz=None) - - Passed an ordinal, translate and convert to a ts. - Note: by definition there cannot be any tz info on the ordinal itself. + Construct a timestamp from a a proleptic Gregorian ordinal. Parameters ---------- @@ -1359,6 +1356,10 @@ class Timestamp(_Timestamp): tz : str, pytz.timezone, dateutil.tz.tzfile or None Time zone for the Timestamp. + Notes + ----- + By definition there cannot be any tz info on the ordinal itself. + Examples -------- >>> pd.Timestamp.fromordinal(737425) @@ -1370,10 +1371,7 @@ class Timestamp(_Timestamp): @classmethod def now(cls, tz=None): """ - Timestamp.now(tz=None) - - Return new Timestamp object representing current time local to - tz. + Return new Timestamp object representing current time local to tz. Parameters ---------- @@ -1397,10 +1395,9 @@ class Timestamp(_Timestamp): @classmethod def today(cls, tz=None): """ - Timestamp.today(cls, tz=None) + Return the current time in the local timezone. - Return the current time in the local timezone. This differs - from datetime.today() in that it can be localized to a + This differs from datetime.today() in that it can be localized to a passed timezone. Parameters @@ -1477,10 +1474,7 @@ class Timestamp(_Timestamp): def strftime(self, format): """ - Timestamp.strftime(format) - - Return a string representing the given POSIX timestamp - controlled by an explicit format string. + Return a formatted string of the Timestamp. Parameters ---------- @@ -2052,7 +2046,9 @@ timedelta}, default 'raise' def tz_localize(self, tz, ambiguous='raise', nonexistent='raise'): """ - Convert naive Timestamp to local time zone, or remove + Localize the Timestamp to a timezone. + + Convert naive Timestamp to local time zone or remove timezone from timezone-aware Timestamp. Parameters @@ -2343,6 +2339,7 @@ default 'raise' def to_julian_date(self) -> np.float64: """ Convert TimeStamp to a Julian Date. + 0 Julian date is noon January 1, 4713 BC. Examples @@ -2374,6 +2371,7 @@ default 'raise' def isoweekday(self): """ Return the day of the week represented by the date. + Monday == 1 ... Sunday == 7. """ # same as super().isoweekday(), but that breaks because of how @@ -2383,6 +2381,7 @@ default 'raise' def weekday(self): """ Return the day of the week represented by the date. + Monday == 0 ... Sunday == 6. """ # same as super().weekday(), but that breaks because of how diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index ea9414aaaa1a8..11c236836e791 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -953,9 +953,9 @@ def freqstr(self) -> str | None: @property # NB: override with cache_readonly in immutable subclasses def inferred_freq(self) -> str | None: """ - Tries to return a string representing a frequency guess, - generated by infer_freq. Returns None if it can't autodetect the - frequency. + Tries to return a string representing a frequency generated by infer_freq. + + Returns None if it can't autodetect the frequency. """ if self.ndim != 1: return None diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index 7a56bba0e58b3..ffd093b86582c 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -810,8 +810,7 @@ def tz_convert(self, tz) -> DatetimeArray: @dtl.ravel_compat def tz_localize(self, tz, ambiguous="raise", nonexistent="raise") -> DatetimeArray: """ - Localize tz-naive Datetime Array/Index to tz-aware - Datetime Array/Index. + Localize tz-naive Datetime Array/Index to tz-aware Datetime Array/Index. This method takes a time zone (tz) naive Datetime Array/Index object and makes this time zone aware. It does not move the time to another @@ -993,8 +992,7 @@ def tz_localize(self, tz, ambiguous="raise", nonexistent="raise") -> DatetimeArr def to_pydatetime(self) -> npt.NDArray[np.object_]: """ - Return Datetime Array/Index as object ndarray of datetime.datetime - objects. + Return an ndarray of datetime.datetime objects. Returns ------- @@ -1122,9 +1120,9 @@ def to_period(self, freq=None) -> PeriodArray: def to_perioddelta(self, freq) -> TimedeltaArray: """ - Calculate TimedeltaArray of difference between index - values and index converted to PeriodArray at specified - freq. Used for vectorized offsets. + Calculate deltas between self values and self converted to Periods at a freq. + + Used for vectorized offsets. Parameters ---------- @@ -1157,8 +1155,7 @@ def to_perioddelta(self, freq) -> TimedeltaArray: def month_name(self, locale=None) -> npt.NDArray[np.object_]: """ - Return the month names of the :class:`~pandas.Series` or - :class:`~pandas.DatetimeIndex` with specified locale. + Return the month names with specified locale. Parameters ---------- @@ -1202,8 +1199,7 @@ def month_name(self, locale=None) -> npt.NDArray[np.object_]: def day_name(self, locale=None) -> npt.NDArray[np.object_]: """ - Return the day names of the :class:`~pandas.Series` or - :class:`~pandas.DatetimeIndex` with specified locale. + Return the day names with specified locale. Parameters ---------- @@ -1262,8 +1258,7 @@ def time(self) -> npt.NDArray[np.object_]: @property def timetz(self) -> npt.NDArray[np.object_]: """ - Returns numpy array of :class:`datetime.time` objects with timezone - information. + Returns numpy array of :class:`datetime.time` objects with timezones. The time part of the Timestamps. """ diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py index 6469dccf6e2d5..6a03530f9f9c7 100644 --- a/pandas/core/arrays/interval.py +++ b/pandas/core/arrays/interval.py @@ -1254,8 +1254,7 @@ def _format_space(self) -> str: @property def left(self): """ - Return the left endpoints of each Interval in the IntervalArray as - an Index. + Return the left endpoints of each Interval in the IntervalArray as an Index. """ from pandas import Index @@ -1264,8 +1263,7 @@ def left(self): @property def right(self): """ - Return the right endpoints of each Interval in the IntervalArray as - an Index. + Return the right endpoints of each Interval in the IntervalArray as an Index. """ from pandas import Index @@ -1274,8 +1272,7 @@ def right(self): @property def length(self) -> Index: """ - Return an Index with entries denoting the length of each Interval in - the IntervalArray. + Return an Index with entries denoting the length of each Interval. """ return self.right - self.left @@ -1367,16 +1364,18 @@ def overlaps(self, other): @property def inclusive(self) -> IntervalInclusiveType: """ - Whether the intervals are inclusive on the left-side, right-side, both or - neither. + String describing the inclusive side the intervals. + + Either ``left``, ``right``, ``both`` or ``neither`. """ return self.dtype.inclusive @property def closed(self) -> IntervalInclusiveType: """ - Whether the intervals are closed on the left-side, right-side, both or - neither. + String describing the inclusive side the intervals. + + Either ``left``, ``right``, ``both`` or ``neither`. """ warnings.warn( "Attribute `closed` is deprecated in favor of `inclusive`.", @@ -1387,8 +1386,7 @@ def closed(self) -> IntervalInclusiveType: _interval_shared_docs["set_closed"] = textwrap.dedent( """ - Return an %(klass)s identical to the current one, but closed on the - specified side. + Return an identical %(klass)s closed on the specified side. .. deprecated:: 1.5.0 @@ -1440,8 +1438,7 @@ def set_closed( _interval_shared_docs["set_inclusive"] = textwrap.dedent( """ - Return an %(klass)s identical to the current one, but closed on the - specified side. + Return an identical %(klass)s but closed on the specified side. .. versionadded:: 1.5 @@ -1497,9 +1494,10 @@ def set_inclusive( _interval_shared_docs[ "is_non_overlapping_monotonic" ] = """ - Return True if the %(klass)s is non-overlapping (no Intervals share - points) and is either monotonic increasing or monotonic decreasing, - else False. + Return a boolean whether the %(klass)s is non-overlapping and monotonic. + + Non-overlapping means (no Intervals share points), and monotonic means + either monotonic increasing or monotonic decreasing. """ # https://github.com/python/mypy/issues/1362 diff --git a/pandas/core/arrays/timedeltas.py b/pandas/core/arrays/timedeltas.py index 5f227cb45a65b..4011f29855949 100644 --- a/pandas/core/arrays/timedeltas.py +++ b/pandas/core/arrays/timedeltas.py @@ -771,8 +771,7 @@ def total_seconds(self) -> npt.NDArray[np.float64]: def to_pytimedelta(self) -> npt.NDArray[np.object_]: """ - Return Timedelta Array/Index as object ndarray of datetime.timedelta - objects. + Return an ndarray of datetime.timedelta objects. Returns ------- @@ -800,8 +799,10 @@ def to_pytimedelta(self) -> npt.NDArray[np.object_]: @property def components(self) -> DataFrame: """ - Return a dataframe of the components (days, hours, minutes, - seconds, milliseconds, microseconds, nanoseconds) of the Timedeltas. + Return a DataFrame of the individual resolution components of the Timedeltas. + + The components (days, hours, minutes seconds, milliseconds, microseconds, + nanoseconds) are returned as columns in a DataFrame. Returns ------- diff --git a/pandas/core/base.py b/pandas/core/base.py index 2fa3f57f950b5..f7e6c4434da32 100644 --- a/pandas/core/base.py +++ b/pandas/core/base.py @@ -1054,8 +1054,7 @@ def is_unique(self) -> bool: @property def is_monotonic(self) -> bool: """ - Return boolean if values in the object are - monotonic_increasing. + Return boolean if values in the object are monotonically increasing. Returns ------- @@ -1072,8 +1071,7 @@ def is_monotonic(self) -> bool: @property def is_monotonic_increasing(self) -> bool: """ - Return boolean if values in the object are - monotonic_increasing. + Return boolean if values in the object are monotonically increasing. Returns ------- @@ -1086,8 +1084,7 @@ def is_monotonic_increasing(self) -> bool: @property def is_monotonic_decreasing(self) -> bool: """ - Return boolean if values in the object are - monotonic_decreasing. + Return boolean if values in the object are monotonically decreasing. Returns ------- diff --git a/pandas/core/frame.py b/pandas/core/frame.py index a541cbfe502fb..1c281f571d422 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -4837,8 +4837,6 @@ def lookup( ) -> np.ndarray: """ Label-based "fancy indexing" function for DataFrame. - Given equal-length arrays of row and column labels, return an - array of the values corresponding to each (row, col) pair. .. deprecated:: 1.2.0 DataFrame.lookup is deprecated, @@ -4846,6 +4844,9 @@ def lookup( For further details see :ref:`Looking up values by index/column labels `. + Given equal-length arrays of row and column labels, return an + array of the values corresponding to each (row, col) pair. + Parameters ---------- row_labels : sequence diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 0a439faed0896..a033b7a3f83d7 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -9970,13 +9970,14 @@ def shift( def slice_shift(self: NDFrameT, periods: int = 1, axis=0) -> NDFrameT: """ Equivalent to `shift` without copying data. - The shifted data will not include the dropped periods and the - shifted axis will be smaller than the original. .. deprecated:: 1.2.0 slice_shift is deprecated, use DataFrame/Series.shift instead. + The shifted data will not include the dropped periods and the + shifted axis will be smaller than the original. + Parameters ---------- periods : int diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 9b4991d32692b..8eac2260448ab 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -329,8 +329,7 @@ class providing the base-class of operations. """ _pipe_template = """ -Apply a function `func` with arguments to this %(klass)s object and return -the function's result. +Apply a ``func`` with arguments to this %(klass)s object and return its result. Use `.pipe` when you want to improve readability by chaining together functions that expect Series, DataFrames, GroupBy or Resampler objects. @@ -381,8 +380,9 @@ class providing the base-class of operations. """ _transform_template = """ -Call function producing a same-indexed %(klass)s on each group and -return a %(klass)s having the same indexes as the original object +Call function producing a same-indexed %(klass)s on each group. + +Returns a %(klass)s having the same indexes as the original object filled with the transformed values. Parameters diff --git a/pandas/core/indexers/objects.py b/pandas/core/indexers/objects.py index beb4db644dd79..c15cbf368c159 100644 --- a/pandas/core/indexers/objects.py +++ b/pandas/core/indexers/objects.py @@ -238,8 +238,7 @@ def get_window_bounds( class FixedForwardWindowIndexer(BaseIndexer): """ - Creates window boundaries for fixed-length windows that include the - current row. + Creates window boundaries for fixed-length windows that include the current row. Examples -------- diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index a212da050e1f1..5881434edef7e 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -271,8 +271,9 @@ def _new_Index(cls, d): class Index(IndexOpsMixin, PandasObject): """ - Immutable sequence used for indexing and alignment. The basic object - storing axis labels for all pandas objects. + Immutable sequence used for indexing and alignment. + + The basic object storing axis labels for all pandas objects. Parameters ---------- @@ -2290,8 +2291,7 @@ def is_monotonic(self) -> bool: @property def is_monotonic_increasing(self) -> bool: """ - Return if the index is monotonic increasing (only equal or - increasing) values. + Return a boolean if the values are equal or increasing. Examples -------- @@ -2307,8 +2307,7 @@ def is_monotonic_increasing(self) -> bool: @property def is_monotonic_decreasing(self) -> bool: """ - Return if the index is monotonic decreasing (only equal or - decreasing) values. + Return a boolean if the values are equal or decreasing. Examples -------- @@ -3810,8 +3809,9 @@ def get_loc(self, key, method=None, tolerance=None): _index_shared_docs[ "get_indexer" ] = """ - Compute indexer and mask for new index given the current index. The - indexer should be then used as an input to ndarray.take to align the + Compute indexer and mask for new index given the current index. + + The indexer should be then used as an input to ndarray.take to align the current data to the new index. Parameters @@ -4580,8 +4580,7 @@ def join( sort: bool = False, ) -> Index | tuple[Index, npt.NDArray[np.intp] | None, npt.NDArray[np.intp] | None]: """ - Compute join_index and indexers to conform data - structures to the new index. + Compute join_index and indexers to conform data structures to the new index. Parameters ---------- @@ -5977,8 +5976,9 @@ def set_value(self, arr, key, value) -> None: _index_shared_docs[ "get_indexer_non_unique" ] = """ - Compute indexer and mask for new index given the current index. The - indexer should be then used as an input to ndarray.take to align the + Compute indexer and mask for new index given the current index. + + The indexer should be then used as an input to ndarray.take to align the current data to the new index. Parameters diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index 3a7adb19f1c01..30c770f32c2dc 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -496,8 +496,9 @@ def _get_time_micros(self) -> npt.NDArray[np.int64]: def to_series(self, keep_tz=lib.no_default, index=None, name=None): """ - Create a Series with both index and values equal to the index keys - useful with map for returning an indexer based on an index. + Create a Series with both index and values equal to the index keys. + + Useful with map for returning an indexer based on an index. Parameters ---------- @@ -826,8 +827,7 @@ def inferred_type(self) -> str: def indexer_at_time(self, time, asof: bool = False) -> npt.NDArray[np.intp]: """ - Return index locations of values at particular time of day - (e.g. 9:30AM). + Return index locations of values at particular time of day. Parameters ---------- @@ -867,8 +867,7 @@ def indexer_between_time( self, start_time, end_time, include_start: bool = True, include_end: bool = True ) -> npt.NDArray[np.intp]: """ - Return index locations of values between particular times of day - (e.g., 9:00-9:30AM). + Return index locations of values between particular times of day. Parameters ---------- @@ -1134,8 +1133,7 @@ def bdate_range( **kwargs, ) -> DatetimeIndex: """ - Return a fixed frequency DatetimeIndex, with business day as the default - frequency. + Return a fixed frequency DatetimeIndex with business day as the default. Parameters ---------- diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index fd6b6ba63d7e0..a0398859abc2b 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -1567,8 +1567,7 @@ def _get_level_number(self, level) -> int: @cache_readonly def is_monotonic_increasing(self) -> bool: """ - return if the index is monotonic increasing (only equal or - increasing) values. + Return a boolean if the values are equal or increasing. """ if any(-1 in code for code in self.codes): return False @@ -1600,8 +1599,7 @@ def is_monotonic_increasing(self) -> bool: @cache_readonly def is_monotonic_decreasing(self) -> bool: """ - return if the index is monotonic decreasing (only equal or - decreasing) values. + Return a boolean if the values are equal or decreasing. """ # monotonic decreasing if and only if reverse is monotonic increasing return self[::-1].is_monotonic_increasing diff --git a/pandas/core/indexes/numeric.py b/pandas/core/indexes/numeric.py index 5731d476cef10..a597bea0eb724 100644 --- a/pandas/core/indexes/numeric.py +++ b/pandas/core/indexes/numeric.py @@ -42,9 +42,10 @@ class NumericIndex(Index): """ - Immutable sequence used for indexing and alignment. The basic object - storing axis labels for all pandas objects. NumericIndex is a special case - of `Index` with purely numpy int/uint/float labels. + Immutable numeric sequence used for indexing and alignment. + + The basic object storing axis labels for all pandas objects. + NumericIndex is a special case of `Index` with purely numpy int/uint/float labels. .. versionadded:: 1.4.0 @@ -309,14 +310,15 @@ def _format_native_types( _num_index_shared_docs[ "class_descr" ] = """ - Immutable sequence used for indexing and alignment. The basic object - storing axis labels for all pandas objects. %(klass)s is a special case - of `Index` with purely %(ltype)s labels. %(extra)s. + Immutable sequence used for indexing and alignment. .. deprecated:: 1.4.0 In pandas v2.0 %(klass)s will be removed and :class:`NumericIndex` used instead. %(klass)s will remain fully functional for the duration of pandas 1.x. + The basic object storing axis labels for all pandas objects. + %(klass)s is a special case of `Index` with purely %(ltype)s labels. %(extra)s. + Parameters ---------- data : array-like (1-dimensional) diff --git a/pandas/core/indexes/timedeltas.py b/pandas/core/indexes/timedeltas.py index 095c5d1b1ba03..12a8f2c0d5a9d 100644 --- a/pandas/core/indexes/timedeltas.py +++ b/pandas/core/indexes/timedeltas.py @@ -47,8 +47,9 @@ ) class TimedeltaIndex(DatetimeTimedeltaMixin): """ - Immutable ndarray of timedelta64 data, represented internally as int64, and - which can be boxed to timedelta objects. + Immutable Index of timedelta64 data. + + Represented internally as int64, and scalars returned Timedelta objects. Parameters ---------- @@ -209,8 +210,7 @@ def timedelta_range( closed=None, ) -> TimedeltaIndex: """ - Return a fixed frequency TimedeltaIndex, with day as the default - frequency. + Return a fixed frequency TimedeltaIndex with day as the default. Parameters ---------- diff --git a/pandas/core/resample.py b/pandas/core/resample.py index 917382544199a..8797324166745 100644 --- a/pandas/core/resample.py +++ b/pandas/core/resample.py @@ -362,8 +362,9 @@ def aggregate(self, func=None, *args, **kwargs): def transform(self, arg, *args, **kwargs): """ - Call function producing a like-indexed Series on each group and return - a Series with the transformed values. + Call function producing a like-indexed Series on each group. + + Return a Series with the transformed values. Parameters ---------- diff --git a/pandas/core/reshape/concat.py b/pandas/core/reshape/concat.py index 523cd56db3e0a..5328c7995ea6f 100644 --- a/pandas/core/reshape/concat.py +++ b/pandas/core/reshape/concat.py @@ -157,8 +157,9 @@ def concat( copy: bool = True, ) -> DataFrame | Series: """ - Concatenate pandas objects along a particular axis with optional set logic - along the other axes. + Concatenate pandas objects along a particular axis. + + Allows optional set logic along the other axes. Can also add a layer of hierarchical indexing on the concatenation axis, which may be useful if the labels are the same (or overlapping) on diff --git a/pandas/core/reshape/pivot.py b/pandas/core/reshape/pivot.py index 03aad0ef64dec..5226c928c6f73 100644 --- a/pandas/core/reshape/pivot.py +++ b/pandas/core/reshape/pivot.py @@ -537,9 +537,10 @@ def crosstab( normalize=False, ) -> DataFrame: """ - Compute a simple cross tabulation of two (or more) factors. By default - computes a frequency table of the factors unless an array of values and an - aggregation function are passed. + Compute a simple cross tabulation of two (or more) factors. + + By default, computes a frequency table of the factors unless an + array of values and an aggregation function are passed. Parameters ---------- diff --git a/pandas/core/series.py b/pandas/core/series.py index 67cdb5d8d72ab..765bf9f7e04f1 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -2642,6 +2642,7 @@ def quantile( def corr(self, other, method="pearson", min_periods=None) -> float: """ Compute correlation with `other` Series, excluding missing values. + The two `Series` objects are not required to be the same length and will be aligned internally before the correlation function is applied. @@ -2716,6 +2717,7 @@ def cov( ) -> float: """ Compute covariance with Series, excluding missing values. + The two `Series` objects are not required to be the same length and will be aligned internally before the covariance is calculated. diff --git a/pandas/core/strings/accessor.py b/pandas/core/strings/accessor.py index 73d5c04ecd652..d50daad9a22b1 100644 --- a/pandas/core/strings/accessor.py +++ b/pandas/core/strings/accessor.py @@ -2015,8 +2015,9 @@ def rstrip(self, to_strip=None): _shared_docs[ "str_removefix" ] = r""" - Remove a %(side)s from an object series. If the %(side)s is not present, - the original string will be returned. + Remove a %(side)s from an object series. + + If the %(side)s is not present, the original string will be returned. Parameters ---------- diff --git a/pandas/errors/__init__.py b/pandas/errors/__init__.py index e3f7e9d454383..d7f5e7aab58ab 100644 --- a/pandas/errors/__init__.py +++ b/pandas/errors/__init__.py @@ -15,21 +15,17 @@ class IntCastingNaNError(ValueError): """ - Raised when attempting an astype operation on an array with NaN to an integer - dtype. + Exception raised when converting (``astype``) an array with NaN to an integer type. """ - pass - class NullFrequencyError(ValueError): """ - Error raised when a null `freq` attribute is used in an operation - that needs a non-null frequency, particularly `DatetimeIndex.shift`, - `TimedeltaIndex.shift`, `PeriodIndex.shift`. - """ + Exception raised when a ``freq`` cannot be null. - pass + Particularly ``DatetimeIndex.shift``, ``TimedeltaIndex.shift``, + ``PeriodIndex.shift``. + """ class PerformanceWarning(Warning): @@ -40,16 +36,17 @@ class PerformanceWarning(Warning): class UnsupportedFunctionCall(ValueError): """ - Exception raised when attempting to call a numpy function - on a pandas object, but that function is not supported by - the object e.g. ``np.cumsum(groupby_object)``. + Exception raised when attempting to call a unsupported numpy function. + + For example, ``np.cumsum(groupby_object)``. """ class UnsortedIndexError(KeyError): """ - Error raised when attempting to get a slice of a MultiIndex, - and the index has not been lexsorted. Subclass of `KeyError`. + Error raised when slicing a MultiIndex which has not been lexsorted. + + Subclass of `KeyError`. """ @@ -124,8 +121,7 @@ class DtypeWarning(Warning): class EmptyDataError(ValueError): """ - Exception that is thrown in `pd.read_csv` (by both the C and - Python engines) when empty data or header is encountered. + Exception raised in ``pd.read_csv`` when empty data or header is encountered. """ @@ -172,8 +168,9 @@ class ParserWarning(Warning): class MergeError(ValueError): """ - Error raised when problems arise during merging due to problems - with input data. Subclass of `ValueError`. + Exception raised when merging data. + + Subclass of ``ValueError``. """ @@ -185,8 +182,7 @@ class AccessorRegistrationWarning(Warning): class AbstractMethodError(NotImplementedError): """ - Raise this error instead of NotImplementedError for abstract methods - while keeping compatibility with Python 2 and Python 3. + Raise this error instead of NotImplementedError for abstract methods. """ def __init__(self, class_instance, methodtype: str = "method") -> None: @@ -243,17 +239,23 @@ class InvalidIndexError(Exception): class DataError(Exception): """ - Exception raised when trying to perform a ohlc on a non-numnerical column. - Or, it can be raised when trying to apply a function to a non-numerical - column on a rolling window. + Exceptionn raised when performing an operation on non-numerical data. + + For example, calling ``ohlc`` on a non-numerical column or a function + on a rolling window. """ class SpecificationError(Exception): """ - Exception raised in two scenarios. The first way is calling agg on a + Exception raised by ``agg`` when the functions are ill-specified. + + The exception raised in two scenarios. + + The first way is calling ``agg`` on a Dataframe or Series using a nested renamer (dict-of-dict). - The second way is calling agg on a Dataframe with duplicated functions + + The second way is calling ``agg`` on a Dataframe with duplicated functions names without assigning column name. Examples @@ -274,9 +276,10 @@ class SpecificationError(Exception): class SettingWithCopyError(ValueError): """ - Exception is raised when trying to set on a copied slice from a dataframe and - the mode.chained_assignment is set to 'raise.' This can happen unintentionally - when chained indexing. + Exception raised when trying to set on a copied slice from a ``DataFrame``. + + The ``mode.chained_assignment`` needs to be set to set to 'raise.' This can + happen unintentionally when chained indexing. For more information on eveluation order, see :ref:`the user guide`. @@ -295,9 +298,11 @@ class SettingWithCopyError(ValueError): class SettingWithCopyWarning(Warning): """ - Warning is raised when trying to set on a copied slice from a dataframe and - the mode.chained_assignment is set to 'warn.' 'Warn' is the default option. - This can happen unintentionally when chained indexing. + Warning raised when trying to set on a copied slice from a ``DataFrame``. + + The ``mode.chained_assignment`` needs to be set to set to 'warn.' + 'Warn' is the default option. This can happen unintentionally when + chained indexing. For more information on eveluation order, see :ref:`the user guide`. @@ -315,10 +320,11 @@ class SettingWithCopyWarning(Warning): class NumExprClobberingError(NameError): """ - Exception is raised when trying to use a built-in numexpr name as a variable name - in a method like query or eval. Eval will throw the error if the engine is set - to 'numexpr'. 'numexpr' is the default engine value for eval if the numexpr package - is installed. + Exception raised when trying to use a built-in numexpr name as a variable name. + + ``eval`` or ``query`` will throw the error if the engine is set + to 'numexpr'. 'numexpr' is the default engine value for these methods if the + numexpr package is installed. Examples -------- @@ -333,9 +339,9 @@ class NumExprClobberingError(NameError): class UndefinedVariableError(NameError): """ - Exception is raised when trying to use an undefined variable name in a method - like query or eval. It will also specific whether the undefined variable is - local or not. + Exception raised by ``query`` or ``eval`` when using an undefined variable name. + + It will also specify whether the undefined variable is local or not. Examples -------- @@ -380,15 +386,18 @@ class IndexingError(Exception): class PyperclipException(RuntimeError): """ - Exception is raised when trying to use methods like to_clipboard() and - read_clipboard() on an unsupported OS/platform. + Exception raised when clipboard functionality is unsupported. + + Raised by ``to_clipboard()`` and ``read_clipboard()``. """ class PyperclipWindowsException(PyperclipException): """ - Exception is raised when pandas is unable to get access to the clipboard handle - due to some other window process is accessing it. + Exception raised when clipboard functionality is unsupported by Windows. + + Access to the clipboard handle would be denied due to some other + window process is accessing it. """ def __init__(self, message: str) -> None: @@ -400,6 +409,7 @@ def __init__(self, message: str) -> None: class CSSWarning(UserWarning): """ Warning is raised when converting css styling fails. + This can be due to the styling not having an equivalent value or because the styling isn't properly formatted. @@ -417,8 +427,7 @@ class CSSWarning(UserWarning): class PossibleDataLossError(Exception): """ - Exception is raised when trying to open a HDFStore file when the file is already - opened. + Exception raised when trying to open a HDFStore file when already opened. Examples -------- @@ -443,14 +452,15 @@ class ClosedFileError(Exception): class IncompatibilityWarning(Warning): """ - Warning is raised when trying to use where criteria on an incompatible - HDF5 file. + Warning raised when trying to use where criteria on an incompatible HDF5 file. """ class AttributeConflictWarning(Warning): """ - Warning is raised when attempting to append an index with a different + Warning raised when index attributes conflict when using HDFStore. + + Occurs when attempting to append an index with a different name than the existing index on an HDFStore or attempting to append an index with a different frequency than the existing index on an HDFStore. """ diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py index 01b4812d3dc2a..9e3f54169d178 100644 --- a/pandas/io/formats/style.py +++ b/pandas/io/formats/style.py @@ -1479,8 +1479,7 @@ def to_string( def set_td_classes(self, classes: DataFrame) -> Styler: """ - Set the DataFrame of strings added to the ``class`` attribute of ```` - HTML elements. + Set the ``class`` attribute of ```` HTML elements. Parameters ---------- @@ -3173,8 +3172,7 @@ def text_gradient( @Substitution(subset=subset) def set_properties(self, subset: Subset | None = None, **kwargs) -> Styler: """ - Set defined CSS-properties to each ```` HTML element within the given - subset. + Set defined CSS-properties to each ```` HTML element for the given subset. Parameters ---------- diff --git a/pandas/io/formats/style_render.py b/pandas/io/formats/style_render.py index dba161cf6d45c..94ce10c03aec9 100644 --- a/pandas/io/formats/style_render.py +++ b/pandas/io/formats/style_render.py @@ -68,6 +68,12 @@ def _gl01_adjust(obj: Any) -> Any: return obj +def _ss06_adjust(obj: Any) -> Any: + """Adjust docstrings for Numpydoc SS06.""" + obj.__doc__ = "\n" + obj.__doc__ + return obj + + class StylerRenderer: """ Base class to process rendering a Styler with a specified jinja2 template. diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index 5c773a424a1c9..a4049eff8ae71 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -1214,8 +1214,9 @@ def append( errors: str = "strict", ) -> None: """ - Append to Table in file. Node must already exist and be Table - format. + Append to Table in file. + + Node must already exist and be Table format. Parameters ---------- diff --git a/pandas/io/stata.py b/pandas/io/stata.py index 80b6db2500d28..3daa6d837349e 100644 --- a/pandas/io/stata.py +++ b/pandas/io/stata.py @@ -1968,8 +1968,7 @@ def data_label(self) -> str: def variable_labels(self) -> dict[str, str]: """ - Return variable labels as a dict, associating each variable name - with corresponding label. + Return a dict associating each variable name with corresponding label. Returns ------- @@ -1979,8 +1978,7 @@ def variable_labels(self) -> dict[str, str]: def value_labels(self) -> dict[str, dict[float, str]]: """ - Return a dict, associating each variable name a dict, associating - each value its corresponding label. + Return a nested dict associating each variable name to its value and label. Returns ------- diff --git a/pandas/plotting/_misc.py b/pandas/plotting/_misc.py index 17763b25329ab..702d78d3807c2 100644 --- a/pandas/plotting/_misc.py +++ b/pandas/plotting/_misc.py @@ -270,8 +270,7 @@ def andrews_curves( **kwargs, ) -> Axes: """ - Generate a matplotlib plot of Andrews curves, for visualising clusters of - multivariate data. + Generate a matplotlib plot for visualising clusters of multivariate data. Andrews curves have the functional form: @@ -543,7 +542,7 @@ def autocorrelation_plot(series: Series, ax: Axes | None = None, **kwargs) -> Ax return plot_backend.autocorrelation_plot(series=series, ax=ax, **kwargs) -class _Options(dict): +class plot_params(dict): """ Stores pandas plotting options. @@ -595,7 +594,7 @@ def _get_canonical_key(self, key): return self._ALIASES.get(key, key) @contextmanager - def use(self, key, value) -> Iterator[_Options]: + def use(self, key, value) -> Iterator[plot_params]: """ Temporarily set a parameter value using the with statement. Aliasing allowed. @@ -606,6 +605,3 @@ def use(self, key, value) -> Iterator[_Options]: yield self finally: self[key] = old_value - - -plot_params = _Options() From 8bc7f3383983b16e590a9609e8cb60cdb73b98c9 Mon Sep 17 00:00:00 2001 From: Matthew Roeschke Date: Wed, 27 Jul 2022 17:32:59 -0700 Subject: [PATCH 2/7] Fix more docs --- pandas/_libs/interval.pyx | 5 +++-- scripts/validate_docstrings.py | 3 ++- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/pandas/_libs/interval.pyx b/pandas/_libs/interval.pyx index 33b96aedde443..0057bda15235b 100644 --- a/pandas/_libs/interval.pyx +++ b/pandas/_libs/interval.pyx @@ -352,8 +352,9 @@ cdef class Interval(IntervalMixin): cdef readonly str inclusive """ - Whether the interval is inclusive on the left-side, right-side, both or - neither. + String describing the inclusive side the intervals. + + Either ``left``, ``right``, ``both`` or ``neither`. """ def __init__(self, left, right, inclusive: str | None = None, closed: None | lib.NoDefault = lib.no_default): diff --git a/scripts/validate_docstrings.py b/scripts/validate_docstrings.py index 3a0c437c918fb..a18f24e37997a 100755 --- a/scripts/validate_docstrings.py +++ b/scripts/validate_docstrings.py @@ -230,7 +230,8 @@ def pandas_validate(func_name: str): Information about the docstring and the errors found. """ func_obj = Validator._load_obj(func_name) - doc_obj = get_doc_object(func_obj) + # Some objects are instances, e.g. IndexSlice, which numpydoc can't validate + doc_obj = get_doc_object(func_obj, doc=func_obj.__doc__) doc = PandasDocstring(func_name, doc_obj) result = validate(doc_obj) From 113edb2068822a23376727bbe3676fae1a3d0f9d Mon Sep 17 00:00:00 2001 From: Matthew Roeschke Date: Thu, 28 Jul 2022 09:32:56 -0700 Subject: [PATCH 3/7] Ignore Styler methods that are jinja objects --- pandas/io/formats/style_render.py | 26 +++++++------------------- scripts/validate_docstrings.py | 13 ++++++++++++- 2 files changed, 19 insertions(+), 20 deletions(-) diff --git a/pandas/io/formats/style_render.py b/pandas/io/formats/style_render.py index 94ce10c03aec9..414bd3b76bd0d 100644 --- a/pandas/io/formats/style_render.py +++ b/pandas/io/formats/style_render.py @@ -62,30 +62,18 @@ class CSSDict(TypedDict): Subset = Union[slice, Sequence, Index] -def _gl01_adjust(obj: Any) -> Any: - """Adjust docstrings for Numpydoc GLO1.""" - obj.__doc__ = "\n" + obj.__doc__ - return obj - - -def _ss06_adjust(obj: Any) -> Any: - """Adjust docstrings for Numpydoc SS06.""" - obj.__doc__ = "\n" + obj.__doc__ - return obj - - class StylerRenderer: """ Base class to process rendering a Styler with a specified jinja2 template. """ - loader = _gl01_adjust(jinja2.PackageLoader("pandas", "io/formats/templates")) - env = _gl01_adjust(jinja2.Environment(loader=loader, trim_blocks=True)) - template_html = _gl01_adjust(env.get_template("html.tpl")) - template_html_table = _gl01_adjust(env.get_template("html_table.tpl")) - template_html_style = _gl01_adjust(env.get_template("html_style.tpl")) - template_latex = _gl01_adjust(env.get_template("latex.tpl")) - template_string = _gl01_adjust(env.get_template("string.tpl")) + loader = jinja2.PackageLoader("pandas", "io/formats/templates") + env = jinja2.Environment(loader=loader, trim_blocks=True) + template_html = env.get_template("html.tpl") + template_html_table = env.get_template("html_table.tpl") + template_html_style = env.get_template("html_style.tpl") + template_latex = env.get_template("latex.tpl") + template_string = env.get_template("string.tpl") def __init__( self, diff --git a/scripts/validate_docstrings.py b/scripts/validate_docstrings.py index a18f24e37997a..cbf02bc0a0156 100755 --- a/scripts/validate_docstrings.py +++ b/scripts/validate_docstrings.py @@ -40,7 +40,16 @@ # With template backend, matplotlib plots nothing matplotlib.use("template") - +# Styler methods are Jinja2 objects who's docstrings we don't own. +IGNORE_VALIDATION = { + "Styler.env", + "Styler.template_html", + "Styler.template_html_style", + "Styler.template_html_table", + "Styler.template_latex", + "Styler.template_string", + "Styler.loader", +} PRIVATE_CLASSES = ["NDFrame", "IndexOpsMixin"] ERROR_MSGS = { "GL04": "Private classes ({mentioned_private_classes}) should not be " @@ -121,6 +130,8 @@ def get_api_items(api_doc_fd): position = None continue item = line.strip() + if item in IGNORE_VALIDATION: + continue func = importlib.import_module(current_module) for part in item.split("."): func = getattr(func, part) From 2b9c6b4c96439f6b6572b31a9f636b6574f48c29 Mon Sep 17 00:00:00 2001 From: Matthew Roeschke Date: Thu, 28 Jul 2022 09:37:11 -0700 Subject: [PATCH 4/7] revert plot_param fix --- pandas/plotting/_misc.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/pandas/plotting/_misc.py b/pandas/plotting/_misc.py index 702d78d3807c2..5bd2e8a53e8e8 100644 --- a/pandas/plotting/_misc.py +++ b/pandas/plotting/_misc.py @@ -542,7 +542,7 @@ def autocorrelation_plot(series: Series, ax: Axes | None = None, **kwargs) -> Ax return plot_backend.autocorrelation_plot(series=series, ax=ax, **kwargs) -class plot_params(dict): +class _Options(dict): """ Stores pandas plotting options. @@ -594,7 +594,7 @@ def _get_canonical_key(self, key): return self._ALIASES.get(key, key) @contextmanager - def use(self, key, value) -> Iterator[plot_params]: + def use(self, key, value) -> Iterator[_Options]: """ Temporarily set a parameter value using the with statement. Aliasing allowed. @@ -605,3 +605,6 @@ def use(self, key, value) -> Iterator[plot_params]: yield self finally: self[key] = old_value + + +plot_params = _Options() From 90e1362e21fb2b0dae56d25d0df945c41166932f Mon Sep 17 00:00:00 2001 From: Matthew Roeschke Date: Thu, 28 Jul 2022 16:02:53 -0700 Subject: [PATCH 5/7] Fix NaT --- pandas/_libs/tslibs/nattype.pyx | 29 ++++++++++++++--------------- 1 file changed, 14 insertions(+), 15 deletions(-) diff --git a/pandas/_libs/tslibs/nattype.pyx b/pandas/_libs/tslibs/nattype.pyx index 93687abdf9153..e733d486517e6 100644 --- a/pandas/_libs/tslibs/nattype.pyx +++ b/pandas/_libs/tslibs/nattype.pyx @@ -446,6 +446,7 @@ class NaTType(_NaT): "weekday", """ Return the day of the week represented by the date. + Monday == 0 ... Sunday == 6. """, ) @@ -453,6 +454,7 @@ class NaTType(_NaT): "isoweekday", """ Return the day of the week represented by the date. + Monday == 1 ... Sunday == 7. """, ) @@ -533,10 +535,7 @@ class NaTType(_NaT): strftime = _make_error_func( "strftime", """ - Timestamp.strftime(format) - - Return a string representing the given POSIX timestamp - controlled by an explicit format string. + Return a formatted string of the Timestamp. Parameters ---------- @@ -680,10 +679,7 @@ class NaTType(_NaT): fromordinal = _make_error_func( "fromordinal", """ - Timestamp.fromordinal(ordinal, freq=None, tz=None) - - Passed an ordinal, translate and convert to a ts. - Note: by definition there cannot be any tz info on the ordinal itself. + Construct a timestamp from a a proleptic Gregorian ordinal. Parameters ---------- @@ -694,6 +690,10 @@ class NaTType(_NaT): tz : str, pytz.timezone, dateutil.tz.tzfile or None Time zone for the Timestamp. + Notes + ----- + By definition there cannot be any tz info on the ordinal itself. + Examples -------- >>> pd.Timestamp.fromordinal(737425) @@ -725,10 +725,8 @@ class NaTType(_NaT): now = _make_nat_func( "now", """ - Timestamp.now(tz=None) + Return new Timestamp object representing current time local to tz. - Return new Timestamp object representing current time local to - tz. Parameters ---------- @@ -749,10 +747,9 @@ class NaTType(_NaT): today = _make_nat_func( "today", """ - Timestamp.today(cls, tz=None) + Return the current time in the local timezone. - Return the current time in the local timezone. This differs - from datetime.today() in that it can be localized to a + This differs from datetime.today() in that it can be localized to a passed timezone. Parameters @@ -1090,7 +1087,9 @@ timedelta}, default 'raise' tz_localize = _make_nat_func( "tz_localize", """ - Convert naive Timestamp to local time zone, or remove + Localize the Timestamp to a timezone. + + Convert naive Timestamp to local time zone or remove timezone from timezone-aware Timestamp. Parameters From 208b026939082bde62e16b26fda3fa9254475d52 Mon Sep 17 00:00:00 2001 From: Matthew Roeschke Date: Thu, 28 Jul 2022 16:44:26 -0700 Subject: [PATCH 6/7] Fix backtick --- pandas/_libs/interval.pyx | 4 ++-- pandas/core/arrays/interval.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/pandas/_libs/interval.pyx b/pandas/_libs/interval.pyx index 0057bda15235b..ec1dbff6903e7 100644 --- a/pandas/_libs/interval.pyx +++ b/pandas/_libs/interval.pyx @@ -354,7 +354,7 @@ cdef class Interval(IntervalMixin): """ String describing the inclusive side the intervals. - Either ``left``, ``right``, ``both`` or ``neither`. + Either ``left``, ``right``, ``both`` or ``neither``. """ def __init__(self, left, right, inclusive: str | None = None, closed: None | lib.NoDefault = lib.no_default): @@ -389,7 +389,7 @@ cdef class Interval(IntervalMixin): .. deprecated:: 1.5.0 - Either ``left``, ``right``, ``both`` or ``neither`. + Either ``left``, ``right``, ``both`` or ``neither``. """ warnings.warn( "Attribute `closed` is deprecated in favor of `inclusive`.", diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py index 6a03530f9f9c7..e7198a95c07f1 100644 --- a/pandas/core/arrays/interval.py +++ b/pandas/core/arrays/interval.py @@ -1366,7 +1366,7 @@ def inclusive(self) -> IntervalInclusiveType: """ String describing the inclusive side the intervals. - Either ``left``, ``right``, ``both`` or ``neither`. + Either ``left``, ``right``, ``both`` or ``neither``. """ return self.dtype.inclusive From 64f4e8c18ea62063bf595e228600b5c964cf0c7a Mon Sep 17 00:00:00 2001 From: Matthew Roeschke Date: Fri, 29 Jul 2022 11:26:50 -0700 Subject: [PATCH 7/7] Fix nat docstring, better pytest param id --- pandas/_libs/tslibs/nattype.pyx | 1 - pandas/tests/scalar/test_nat.py | 1 + 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/pandas/_libs/tslibs/nattype.pyx b/pandas/_libs/tslibs/nattype.pyx index e733d486517e6..b05b0ba636251 100644 --- a/pandas/_libs/tslibs/nattype.pyx +++ b/pandas/_libs/tslibs/nattype.pyx @@ -727,7 +727,6 @@ class NaTType(_NaT): """ Return new Timestamp object representing current time local to tz. - Parameters ---------- tz : str or timezone object, default None diff --git a/pandas/tests/scalar/test_nat.py b/pandas/tests/scalar/test_nat.py index 873103b01f64d..1a07c02f4024a 100644 --- a/pandas/tests/scalar/test_nat.py +++ b/pandas/tests/scalar/test_nat.py @@ -320,6 +320,7 @@ def test_overlap_public_nat_methods(klass, expected): _get_overlap_public_nat_methods(Timestamp, True) + _get_overlap_public_nat_methods(Timedelta, True) ), + ids=lambda x: f"{x[0].__name__}.{x[1]}", ) def test_nat_doc_strings(compare): # see gh-17327