Skip to content

Commit 23ff40e

Browse files
author
cloudboat
committed
fix line too long
1 parent bb2e215 commit 23ff40e

File tree

2 files changed

+597
-23
lines changed

2 files changed

+597
-23
lines changed

pandas/core/indexes/datetimelike.py

Lines changed: 271 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -36,9 +36,7 @@
3636
NullFrequencyError,
3737
)
3838
from pandas.util._decorators import (
39-
Appender,
4039
cache_readonly,
41-
doc,
4240
)
4341

4442
from pandas.core.dtypes.common import (
@@ -57,12 +55,10 @@
5755
PeriodArray,
5856
TimedeltaArray,
5957
)
60-
from pandas.core.arrays.datetimelike import DatetimeLikeArrayMixin
6158
import pandas.core.common as com
6259
import pandas.core.indexes.base as ibase
6360
from pandas.core.indexes.base import (
6461
Index,
65-
_index_shared_docs,
6662
)
6763
from pandas.core.indexes.extension import NDArrayBackedExtensionIndex
6864
from pandas.core.indexes.range import RangeIndex
@@ -92,8 +88,43 @@ class DatetimeIndexOpsMixin(NDArrayBackedExtensionIndex, ABC):
9288
_can_hold_strings = False
9389
_data: DatetimeArray | TimedeltaArray | PeriodArray
9490

95-
@doc(DatetimeLikeArrayMixin.mean)
9691
def mean(self, *, skipna: bool = True, axis: int | None = 0):
92+
"""
93+
Return the mean value of the Array.
94+
Parameters
95+
----------
96+
skipna : bool, default True
97+
Whether to ignore any NaT elements.
98+
axis : int, optional, default 0
99+
Axis for the function to be applied on.
100+
Returns
101+
-------
102+
scalar
103+
Timestamp or Timedelta.
104+
See Also
105+
--------
106+
numpy.ndarray.mean : Returns the average of array elements along a given axis.
107+
Series.mean : Return the mean value in a Series.
108+
Notes
109+
-----
110+
mean is only defined for Datetime and Timedelta dtypes, not for Period.
111+
Examples
112+
--------
113+
For :class:`pandas.DatetimeIndex`:
114+
>>> idx = pd.date_range("2001-01-01 00:00", periods=3)
115+
>>> idx
116+
DatetimeIndex(['2001-01-01', '2001-01-02', '2001-01-03'],
117+
dtype='datetime64[ns]', freq='D')
118+
>>> idx.mean()
119+
Timestamp('2001-01-02 00:00:00')
120+
For :class:`pandas.TimedeltaIndex`:
121+
>>> tdelta_idx = pd.to_timedelta([1, 2, 3], unit="D")
122+
>>> tdelta_idx
123+
TimedeltaIndex(['1 days', '2 days', '3 days'],
124+
dtype='timedelta64[ns]', freq=None)
125+
>>> tdelta_idx.mean()
126+
Timedelta('2 days 00:00:00')
127+
"""
97128
return self._data.mean(skipna=skipna, axis=axis)
98129

99130
@property
@@ -136,8 +167,30 @@ def asi8(self) -> npt.NDArray[np.int64]:
136167
return self._data.asi8
137168

138169
@property
139-
@doc(DatetimeLikeArrayMixin.freqstr)
140170
def freqstr(self) -> str:
171+
"""
172+
Return the frequency object as a string if it's set, otherwise None.
173+
See Also
174+
--------
175+
DatetimeIndex.inferred_freq : Returns a string representing a frequency
176+
generated by infer_freq.
177+
Examples
178+
--------
179+
For DatetimeIndex:
180+
>>> idx = pd.DatetimeIndex(["1/1/2020 10:00:00+00:00"], freq="D")
181+
>>> idx.freqstr
182+
'D'
183+
The frequency can be inferred if there are more than 2 points:
184+
>>> idx = pd.DatetimeIndex(
185+
... ["2018-01-01", "2018-01-03", "2018-01-05"], freq="infer"
186+
... )
187+
>>> idx.freqstr
188+
'2D'
189+
For PeriodIndex:
190+
>>> idx = pd.PeriodIndex(["2023-1", "2023-2", "2023-3"], freq="M")
191+
>>> idx.freqstr
192+
'M'
193+
"""
141194
from pandas import PeriodIndex
142195

143196
if self._data.freqstr is not None and isinstance(
@@ -153,8 +206,10 @@ def freqstr(self) -> str:
153206
def _resolution_obj(self) -> Resolution: ...
154207

155208
@cache_readonly
156-
@doc(DatetimeLikeArrayMixin.resolution)
157209
def resolution(self) -> str:
210+
"""
211+
Returns day, hour, minute, second, millisecond or microsecond
212+
"""
158213
return self._data.resolution
159214

160215
# ------------------------------------------------------------------------
@@ -199,8 +254,35 @@ def equals(self, other: Any) -> bool:
199254

200255
return np.array_equal(self.asi8, other.asi8)
201256

202-
@Appender(Index.__contains__.__doc__)
203257
def __contains__(self, key: Any) -> bool:
258+
"""
259+
Return a boolean indicating whether the provided key is in the index.
260+
Parameters
261+
----------
262+
key : label
263+
The key to check if it is present in the index.
264+
Returns
265+
-------
266+
bool
267+
Whether the key search is in the index.
268+
Raises
269+
------
270+
TypeError
271+
If the key is not hashable.
272+
See Also
273+
--------
274+
Index.isin : Returns an ndarray of boolean dtype indicating whether the
275+
list-like key is in the index.
276+
Examples
277+
--------
278+
>>> idx = pd.Index([1, 2, 3, 4])
279+
>>> idx
280+
Index([1, 2, 3, 4], dtype='int64')
281+
>>> 2 in idx
282+
True
283+
>>> 6 in idx
284+
False
285+
"""
204286
hash(key)
205287
try:
206288
self.get_loc(key)
@@ -243,8 +325,17 @@ def _format_attrs(self):
243325
attrs.append(("freq", freq))
244326
return attrs
245327

246-
@Appender(Index._summary.__doc__)
247328
def _summary(self, name=None) -> str:
329+
"""
330+
Return a summarized representation.
331+
Parameters
332+
----------
333+
name : str
334+
name to use in the summary representation
335+
Returns
336+
-------
337+
String with a summarized representation of the index
338+
"""
248339
result = super()._summary(name=name)
249340
if self.freq:
250341
result += f"\nFreq: {self.freqstr}"
@@ -405,8 +496,10 @@ def shift(self, periods: int = 1, freq=None) -> Self:
405496

406497
# --------------------------------------------------------------------
407498

408-
@doc(Index._maybe_cast_listlike_indexer)
409499
def _maybe_cast_listlike_indexer(self, keyarr):
500+
"""
501+
Analogue to maybe_cast_indexer for get_indexer instead of get_loc.
502+
"""
410503
try:
411504
res = self._data._validate_listlike(keyarr, allow_object=True)
412505
except (ValueError, TypeError):
@@ -497,8 +590,29 @@ def values(self) -> np.ndarray:
497590
data.flags.writeable = False
498591
return data
499592

500-
@doc(DatetimeIndexOpsMixin.shift)
501593
def shift(self, periods: int = 1, freq=None) -> Self:
594+
"""
595+
Shift index by desired number of time frequency increments.
596+
This method is for shifting the values of datetime-like indexes
597+
by a specified time increment a given number of times.
598+
Parameters
599+
----------
600+
periods : int, default 1
601+
Number of periods (or increments) to shift by,
602+
can be positive or negative.
603+
freq : pandas.DateOffset, pandas.Timedelta or string, optional
604+
Frequency increment to shift by.
605+
If None, the index is shifted by its own `freq` attribute.
606+
Offset aliases are valid strings, e.g., 'D', 'W', 'M' etc.
607+
Returns
608+
-------
609+
pandas.DatetimeIndex
610+
Shifted index.
611+
See Also
612+
--------
613+
Index.shift : Shift values of Index.
614+
PeriodIndex.shift : Shift values of PeriodIndex.
615+
"""
502616
if freq is not None and freq != self.freq:
503617
if isinstance(freq, str):
504618
freq = to_offset(freq)
@@ -524,8 +638,28 @@ def shift(self, periods: int = 1, freq=None) -> Self:
524638
return type(self)._simple_new(result, name=self.name)
525639

526640
@cache_readonly
527-
@doc(DatetimeLikeArrayMixin.inferred_freq)
528641
def inferred_freq(self) -> str | None:
642+
"""
643+
Tries to return a string representing a frequency generated by infer_freq.
644+
Returns None if it can't autodetect the frequency.
645+
See Also
646+
--------
647+
DatetimeIndex.freqstr : Return the frequency object as a string if it's set,
648+
otherwise None.
649+
Examples
650+
--------
651+
For DatetimeIndex:
652+
>>> idx = pd.DatetimeIndex(["2018-01-01", "2018-01-03", "2018-01-05"])
653+
>>> idx.inferred_freq
654+
'2D'
655+
For TimedeltaIndex:
656+
>>> tdelta_idx = pd.to_timedelta(["0 days", "10 days", "20 days"])
657+
>>> tdelta_idx
658+
TimedeltaIndex(['0 days', '10 days', '20 days'],
659+
dtype='timedelta64[ns]', freq=None)
660+
>>> tdelta_idx.inferred_freq
661+
'10D'
662+
"""
529663
return self._data.inferred_freq
530664

531665
# --------------------------------------------------------------------
@@ -816,14 +950,100 @@ def _get_insert_freq(self, loc: int, item):
816950
freq = self.freq
817951
return freq
818952

819-
@doc(NDArrayBackedExtensionIndex.delete)
820953
def delete(self, loc) -> Self:
954+
"""
955+
Make new Index with passed location(-s) deleted.
956+
Parameters
957+
----------
958+
loc : int or list of int
959+
Location of item(-s) which will be deleted.
960+
Use a list of locations to delete more than one value at the same time.
961+
Returns
962+
-------
963+
Index
964+
Will be same type as self, except for RangeIndex.
965+
See Also
966+
--------
967+
numpy.delete : Delete any rows and column from NumPy array (ndarray).
968+
Examples
969+
--------
970+
>>> idx = pd.Index(["a", "b", "c"])
971+
>>> idx.delete(1)
972+
Index(['a', 'c'], dtype='str')
973+
>>> idx = pd.Index(["a", "b", "c"])
974+
>>> idx.delete([0, 2])
975+
Index(['b'], dtype='str')
976+
Make new Index with passed location(-s) deleted.
977+
Parameters
978+
----------
979+
loc : int or list of int
980+
Location of item(-s) which will be deleted.
981+
Use a list of locations to delete more than one value at the same time.
982+
Returns
983+
-------
984+
Index
985+
Will be same type as self, except for RangeIndex.
986+
See Also
987+
--------
988+
numpy.delete : Delete any rows and column from NumPy array (ndarray).
989+
Examples
990+
--------
991+
>>> idx = pd.Index(["a", "b", "c"])
992+
>>> idx.delete(1)
993+
Index(['a', 'c'], dtype='str')
994+
>>> idx = pd.Index(["a", "b", "c"])
995+
>>> idx.delete([0, 2])
996+
Index(['b'], dtype='str')
997+
"""
821998
result = super().delete(loc)
822999
result._data._freq = self._get_delete_freq(loc)
8231000
return result
8241001

825-
@doc(NDArrayBackedExtensionIndex.insert)
8261002
def insert(self, loc: int, item):
1003+
"""
1004+
Make new Index inserting new item at location.
1005+
Follows Python numpy.insert semantics for negative values.
1006+
Parameters
1007+
----------
1008+
loc : int
1009+
The integer location where the new item will be inserted.
1010+
item : object
1011+
The new item to be inserted into the Index.
1012+
Returns
1013+
-------
1014+
Index
1015+
Returns a new Index object resulting from inserting the specified item at
1016+
the specified location within the original Index.
1017+
See Also
1018+
--------
1019+
Index.append : Append a collection of Indexes together.
1020+
Examples
1021+
--------
1022+
>>> idx = pd.Index(["a", "b", "c"])
1023+
>>> idx.insert(1, "x")
1024+
Index(['a', 'x', 'b', 'c'], dtype='str')
1025+
Make new Index inserting new item at location.
1026+
Follows Python numpy.insert semantics for negative values.
1027+
Parameters
1028+
----------
1029+
loc : int
1030+
The integer location where the new item will be inserted.
1031+
item : object
1032+
The new item to be inserted into the Index.
1033+
Returns
1034+
-------
1035+
Index
1036+
Returns a new Index object resulting from inserting the specified item at
1037+
the specified location within the original Index.
1038+
See Also
1039+
--------
1040+
Index.append : Append a collection of Indexes together.
1041+
Examples
1042+
--------
1043+
>>> idx = pd.Index(["a", "b", "c"])
1044+
>>> idx.insert(1, "x")
1045+
Index(['a', 'x', 'b', 'c'], dtype='str')
1046+
"""
8271047
result = super().insert(loc, item)
8281048
if isinstance(result, type(self)):
8291049
# i.e. parent class method did not cast
@@ -833,7 +1053,6 @@ def insert(self, loc: int, item):
8331053
# --------------------------------------------------------------------
8341054
# NDArray-Like Methods
8351055

836-
@Appender(_index_shared_docs["take"] % _index_doc_kwargs)
8371056
def take(
8381057
self,
8391058
indices,
@@ -842,6 +1061,43 @@ def take(
8421061
fill_value=None,
8431062
**kwargs,
8441063
) -> Self:
1064+
"""
1065+
Return a new Index of the values selected by the indices.
1066+
For internal compatibility with numpy arrays.
1067+
Parameters
1068+
----------
1069+
indices : array-like
1070+
Indices to be taken.
1071+
axis : int, optional
1072+
The axis over which to select values, always 0.
1073+
allow_fill : bool, default True
1074+
How to handle negative values in `indices`.
1075+
* False: negative values in `indices` indicate positional indices
1076+
from the right (the default). This is similar to
1077+
:func:`numpy.take`.
1078+
* True: negative values in `indices` indicate
1079+
missing values. These values are set to `fill_value`. Any other
1080+
other negative values raise a ``ValueError``.
1081+
fill_value : scalar, default None
1082+
If allow_fill=True and fill_value is not None, indices specified by
1083+
-1 are regarded as NA. If Index doesn't hold NA, raise ValueError.
1084+
**kwargs
1085+
Required for compatibility with numpy.
1086+
Returns
1087+
-------
1088+
Index
1089+
An index formed of elements at the given indices. Will be the same
1090+
type as self, except for RangeIndex.
1091+
See Also
1092+
--------
1093+
numpy.ndarray.take: Return an array formed from the
1094+
elements of a at the given indices.
1095+
Examples
1096+
--------
1097+
>>> idx = pd.Index(["a", "b", "c"])
1098+
>>> idx.take([2, 2, 1, 2])
1099+
Index(['c', 'c', 'b', 'c'], dtype='str')
1100+
"""
8451101
nv.validate_take((), kwargs)
8461102
indices = np.asarray(indices, dtype=np.intp)
8471103

0 commit comments

Comments
 (0)