Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/pandas/core/series.py: 29%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1155 statements  

1""" 

2Data structure for 1-dimensional cross-sectional and time series data 

3""" 

4 

5from __future__ import annotations 

6 

7from collections.abc import ( 

8 Callable, 

9 Hashable, 

10 Iterable, 

11 Mapping, 

12 Sequence, 

13) 

14import functools 

15import operator 

16import sys 

17from typing import ( 

18 IO, 

19 TYPE_CHECKING, 

20 Any, 

21 Literal, 

22 Self, 

23 cast, 

24 overload, 

25) 

26import warnings 

27 

28import numpy as np 

29 

30from pandas._libs import ( 

31 lib, 

32 properties, 

33 reshape, 

34) 

35from pandas._libs.lib import is_range_indexer 

36from pandas.compat import CHAINED_WARNING_DISABLED 

37from pandas.compat._constants import ( 

38 REF_COUNT, 

39 REF_COUNT_METHOD, 

40) 

41from pandas.compat._optional import import_optional_dependency 

42from pandas.compat.numpy import function as nv 

43from pandas.errors import ( 

44 ChainedAssignmentError, 

45 InvalidIndexError, 

46 Pandas4Warning, 

47) 

48from pandas.errors.cow import ( 

49 _chained_assignment_method_update_msg, 

50 _chained_assignment_msg, 

51) 

52from pandas.util._decorators import ( 

53 deprecate_nonkeyword_arguments, 

54 set_module, 

55) 

56from pandas.util._exceptions import ( 

57 find_stack_level, 

58) 

59from pandas.util._validators import ( 

60 validate_ascending, 

61 validate_bool_kwarg, 

62 validate_percentile, 

63) 

64 

65from pandas.core.dtypes.astype import astype_is_view 

66from pandas.core.dtypes.cast import ( 

67 LossySetitemError, 

68 construct_1d_arraylike_from_scalar, 

69 find_common_type, 

70 infer_dtype_from, 

71 maybe_box_native, 

72 maybe_unbox_numpy_scalar, 

73) 

74from pandas.core.dtypes.common import ( 

75 is_dict_like, 

76 is_float, 

77 is_integer, 

78 is_iterator, 

79 is_list_like, 

80 is_object_dtype, 

81 is_scalar, 

82 pandas_dtype, 

83 validate_all_hashable, 

84) 

85from pandas.core.dtypes.dtypes import ( 

86 DatetimeTZDtype, 

87 ExtensionDtype, 

88 IntervalDtype, 

89 PeriodDtype, 

90) 

91from pandas.core.dtypes.generic import ( 

92 ABCDataFrame, 

93 ABCSeries, 

94) 

95from pandas.core.dtypes.inference import is_hashable 

96from pandas.core.dtypes.missing import ( 

97 isna, 

98 na_value_for_dtype, 

99 notna, 

100 remove_na_arraylike, 

101) 

102 

103from pandas.core import ( 

104 algorithms, 

105 base, 

106 common as com, 

107 nanops, 

108 ops, 

109 roperator, 

110) 

111from pandas.core.accessor import Accessor 

112from pandas.core.apply import SeriesApply 

113from pandas.core.arrays import ExtensionArray 

114from pandas.core.arrays.arrow import ( 

115 ListAccessor, 

116 StructAccessor, 

117) 

118from pandas.core.arrays.categorical import CategoricalAccessor 

119from pandas.core.arrays.sparse import SparseAccessor 

120from pandas.core.construction import ( 

121 array as pd_array, 

122 extract_array, 

123 sanitize_array, 

124) 

125from pandas.core.generic import NDFrame 

126from pandas.core.indexers import ( 

127 disallow_ndim_indexing, 

128 unpack_1tuple, 

129) 

130from pandas.core.indexes.accessors import CombinedDatetimelikeProperties 

131from pandas.core.indexes.api import ( 

132 DatetimeIndex, 

133 Index, 

134 MultiIndex, 

135 PeriodIndex, 

136 default_index, 

137 ensure_index, 

138 maybe_sequence_to_range, 

139) 

140import pandas.core.indexes.base as ibase 

141from pandas.core.indexes.multi import maybe_droplevels 

142from pandas.core.indexing import ( 

143 check_bool_indexer, 

144 check_dict_or_set_indexers, 

145) 

146from pandas.core.internals import SingleBlockManager 

147from pandas.core.methods import selectn 

148from pandas.core.sorting import ( 

149 ensure_key_mapped, 

150 nargsort, 

151) 

152from pandas.core.strings.accessor import StringMethods 

153from pandas.core.tools.datetimes import to_datetime 

154 

155from pandas.io._util import ( 

156 arrow_table_to_pandas, 

157 suppress_pyarrow_values_warning, 

158) 

159import pandas.io.formats.format as fmt 

160from pandas.io.formats.info import ( 

161 SeriesInfo, 

162) 

163import pandas.plotting 

164 

165if TYPE_CHECKING: 

166 from pandas._libs.internals import BlockValuesRefs 

167 from pandas._typing import ( 

168 AggFuncType, 

169 AnyAll, 

170 AnyArrayLike, 

171 ArrayLike, 

172 ArrowArrayExportable, 

173 ArrowStreamExportable, 

174 Axis, 

175 AxisInt, 

176 CorrelationMethod, 

177 DropKeep, 

178 Dtype, 

179 DtypeObj, 

180 FilePath, 

181 Frequency, 

182 IgnoreRaise, 

183 IndexKeyFunc, 

184 IndexLabel, 

185 Level, 

186 ListLike, 

187 MutableMappingT, 

188 NaPosition, 

189 NumpySorter, 

190 NumpyValueArrayLike, 

191 QuantileInterpolation, 

192 ReindexMethod, 

193 Renamer, 

194 Scalar, 

195 SortKind, 

196 StorageOptions, 

197 Suffixes, 

198 ToTimestampHow, 

199 ValueKeyFunc, 

200 WriteBuffer, 

201 npt, 

202 ) 

203 

204 from pandas.core.frame import DataFrame 

205 from pandas.core.groupby.generic import SeriesGroupBy 

206 

207__all__ = ["Series"] 

208 

209# ---------------------------------------------------------------------- 

210# Series class 

211 

212 

213# error: Cannot override final attribute "ndim" (previously declared in base 

214# class "NDFrame") 

215# error: Cannot override final attribute "size" (previously declared in base 

216# class "NDFrame") 

217# definition in base class "NDFrame" 

218@set_module("pandas") 

219class Series(base.IndexOpsMixin, NDFrame): # type: ignore[misc] 

220 """ 

221 One-dimensional ndarray with axis labels (including time series). 

222 

223 Labels need not be unique but must be a hashable type. The object 

224 supports both integer- and label-based indexing and provides a host of 

225 methods for performing operations involving the index. Statistical 

226 methods from ndarray have been overridden to automatically exclude 

227 missing data (currently represented as NaN). 

228 

229 Operations between Series (+, -, /, \\*, \\*\\*) align values based on their 

230 associated index values-- they need not be the same length. The result 

231 index will be the sorted union of the two indexes. 

232 

233 Parameters 

234 ---------- 

235 data : array-like, Iterable, dict, or scalar value 

236 Contains data stored in Series. If data is a dict, argument order is 

237 maintained. Unordered sets are not supported. 

238 index : array-like or Index (1d) 

239 Values must be hashable and have the same length as `data`. 

240 Non-unique index values are allowed. Will default to 

241 RangeIndex (0, 1, 2, ..., n) if not provided. If data is dict-like 

242 and index is None, then the keys in the data are used as the index. If the 

243 index is not None, the resulting Series is reindexed with the index values. 

244 dtype : str, numpy.dtype, or ExtensionDtype, optional 

245 Data type for the output Series. If not specified, this will be 

246 inferred from `data`. 

247 See the :ref:`user guide <basics.dtypes>` for more usages. 

248 name : Hashable, default None 

249 The name to give to the Series. 

250 copy : bool, default None 

251 Whether to copy input data, only relevant for array, Series, and Index 

252 inputs (for other input, e.g. a list, a new array is created anyway). 

253 Defaults to True for array input and False for Index/Series. 

254 Even when False for Index/Series, a shallow copy of the data is made. 

255 Set to False to avoid copying array input at your own risk (if you 

256 know the input data won't be modified elsewhere). 

257 Set to True to force copying Series/Index input up front. 

258 

259 See Also 

260 -------- 

261 DataFrame : Two-dimensional, size-mutable, potentially heterogeneous tabular data. 

262 Index : Immutable sequence used for indexing and alignment. 

263 

264 Notes 

265 ----- 

266 Please reference the :ref:`User Guide <basics.series>` for more information. 

267 

268 NumPy arrays with ``dtype=object`` may be inferred to a more specific dtype 

269 (e.g. strings or datetimes) rather than keeping object dtype, similar to 

270 passing a Python list. Pass ``dtype=object`` when you need object dtype. 

271 The same inference rules apply when building an :class:`Index` from such an 

272 array. 

273 

274 Examples 

275 -------- 

276 Constructing Series from a dictionary with an Index specified 

277 

278 >>> d = {"a": 1, "b": 2, "c": 3} 

279 >>> ser = pd.Series(data=d, index=["a", "b", "c"]) 

280 >>> ser 

281 a 1 

282 b 2 

283 c 3 

284 dtype: int64 

285 

286 The keys of the dictionary match with the Index values, hence the Index 

287 values have no effect. 

288 

289 >>> d = {"a": 1, "b": 2, "c": 3} 

290 >>> ser = pd.Series(data=d, index=["x", "y", "z"]) 

291 >>> ser 

292 x NaN 

293 y NaN 

294 z NaN 

295 dtype: float64 

296 

297 Note that the Index is first built with the keys from the dictionary. 

298 After this the Series is reindexed with the given Index values, hence we 

299 get all NaN as a result. 

300 

301 Constructing Series from a list with `copy=False`. 

302 

303 >>> r = [1, 2] 

304 >>> ser = pd.Series(r, copy=False) 

305 >>> ser.iloc[0] = 999 

306 >>> r 

307 [1, 2] 

308 >>> ser 

309 0 999 

310 1 2 

311 dtype: int64 

312 

313 Due to input data type the Series has a `copy` of 

314 the original data even though `copy=False`, so 

315 the data is unchanged. 

316 

317 Constructing Series from a 1d ndarray with `copy=False`. 

318 

319 >>> r = np.array([1, 2]) 

320 >>> ser = pd.Series(r, copy=False) 

321 >>> ser.iloc[0] = 999 

322 >>> r 

323 array([999, 2]) 

324 >>> ser 

325 0 999 

326 1 2 

327 dtype: int64 

328 

329 Due to input data type the Series has a `view` on 

330 the original data, so 

331 the data is changed as well. 

332 """ 

333 

334 _typ = "series" 

335 _HANDLED_TYPES = (Index, ExtensionArray, np.ndarray) 

336 

337 _name: Hashable 

338 _metadata: list[str] = ["_name"] 

339 _internal_names_set = {"index", "name"} | NDFrame._internal_names_set 

340 _accessors = {"dt", "cat", "str", "sparse"} 

341 _hidden_attrs = ( 

342 base.IndexOpsMixin._hidden_attrs | NDFrame._hidden_attrs | frozenset([]) 

343 ) 

344 

345 # similar to __array_priority__, positions Series after DataFrame 

346 # but before Index and ExtensionArray. Should NOT be overridden by subclasses. 

347 __pandas_priority__ = 3000 

348 

349 # Override cache_readonly bc Series is mutable 

350 hasnans = property( 

351 # error: "Callable[[IndexOpsMixin], bool]" has no attribute "fget" 

352 base.IndexOpsMixin.hasnans.fget, # type: ignore[attr-defined] 

353 doc=base.IndexOpsMixin.hasnans.__doc__, 

354 ) 

355 _mgr: SingleBlockManager 

356 

357 # ---------------------------------------------------------------------- 

358 # Constructors 

359 

360 def __init__( 

361 self, 

362 data=None, 

363 index=None, 

364 dtype: Dtype | None = None, 

365 name=None, 

366 copy: bool | None = None, 

367 ) -> None: 

368 allow_mgr = False 

369 if ( 

370 isinstance(data, SingleBlockManager) 

371 and index is None 

372 and dtype is None 

373 and (copy is False or copy is None) 

374 ): 

375 if not allow_mgr: 

376 # GH#52419 

377 warnings.warn( 

378 f"Passing a {type(data).__name__} to {type(self).__name__} " 

379 "is deprecated and will raise in a future version. " 

380 "Use public APIs instead.", 

381 Pandas4Warning, 

382 stacklevel=2, 

383 ) 

384 data = data.copy(deep=False) 

385 # GH#33357 called with just the SingleBlockManager 

386 NDFrame.__init__(self, data) 

387 self.name = name 

388 return 

389 

390 if isinstance(data, (ExtensionArray, np.ndarray)): 

391 if copy is not False: 

392 if dtype is None or astype_is_view(data.dtype, pandas_dtype(dtype)): 

393 data = data.copy() 

394 copy = False 

395 if copy is None: 

396 copy = False 

397 

398 if isinstance(data, SingleBlockManager) and not copy: 

399 data = data.copy(deep=False) 

400 

401 if not allow_mgr: 

402 warnings.warn( 

403 f"Passing a {type(data).__name__} to {type(self).__name__} " 

404 "is deprecated and will raise in a future version. " 

405 "Use public APIs instead.", 

406 Pandas4Warning, 

407 stacklevel=2, 

408 ) 

409 allow_mgr = True 

410 

411 name = ibase.maybe_extract_name(name, data, type(self)) 

412 

413 if index is not None: 

414 index = ensure_index(index) 

415 

416 if dtype is not None: 

417 dtype = self._validate_dtype(dtype) 

418 

419 if data is None: 

420 index = index if index is not None else default_index(0) 

421 if len(index) or dtype is not None: 

422 data = na_value_for_dtype(pandas_dtype(dtype), compat=False) 

423 else: 

424 data = [] 

425 

426 if isinstance(data, MultiIndex): 

427 raise NotImplementedError( 

428 "initializing a Series from a MultiIndex is not supported" 

429 ) 

430 

431 refs = None 

432 if isinstance(data, Index): 

433 if dtype is not None: 

434 data = data.astype(dtype) 

435 if not copy: 

436 refs = data._references 

437 

438 elif isinstance(data, np.ndarray): 

439 if len(data.dtype): 

440 # GH#13296 we are dealing with a compound dtype, which 

441 # should be treated as 2D 

442 raise ValueError( 

443 "Cannot construct a Series from an ndarray with " 

444 "compound dtype. Use DataFrame instead." 

445 ) 

446 elif isinstance(data, Series): 

447 if index is None: 

448 index = data.index 

449 data = data._mgr.copy(deep=False) 

450 else: 

451 data = data.reindex(index) 

452 data = data._mgr 

453 if data._has_no_reference(0): 

454 copy = False 

455 elif isinstance(data, Mapping): 

456 data, index = self._init_dict(data, index, dtype) 

457 dtype = None 

458 copy = False 

459 elif isinstance(data, SingleBlockManager): 

460 if index is None: 

461 index = data.index 

462 elif not data.index.equals(index) or copy: 

463 # GH#19275 SingleBlockManager input should only be called 

464 # internally 

465 raise AssertionError( 

466 "Cannot pass both SingleBlockManager " 

467 "`data` argument and a different " 

468 "`index` argument. `copy` must be False." 

469 ) 

470 

471 if not allow_mgr: 

472 warnings.warn( 

473 f"Passing a {type(data).__name__} to {type(self).__name__} " 

474 "is deprecated and will raise in a future version. " 

475 "Use public APIs instead.", 

476 Pandas4Warning, 

477 stacklevel=2, 

478 ) 

479 allow_mgr = True 

480 

481 elif isinstance(data, ExtensionArray): 

482 pass 

483 else: 

484 if isinstance(data, ABCDataFrame): 

485 raise ValueError( 

486 "Cannot construct a Series from a DataFrame. To select a " 

487 "single column, use df.iloc[:, 0]." 

488 ) 

489 data = com.maybe_iterable_to_list(data) 

490 if is_list_like(data) and not len(data) and dtype is None: 

491 # GH 29405: Pre-2.0, this defaulted to float. 

492 dtype = np.dtype(object) 

493 

494 if index is None: 

495 if not is_list_like(data): 

496 data = [data] 

497 index = default_index(len(data)) 

498 elif is_list_like(data): 

499 com.require_length_match(data, index) 

500 

501 # create/copy the manager 

502 if isinstance(data, SingleBlockManager): 

503 if dtype is not None: 

504 if not astype_is_view(data.dtype, pandas_dtype(dtype)): 

505 copy = False 

506 data = data.astype(dtype=dtype) 

507 if copy: 

508 data = data.copy(deep=True) 

509 else: 

510 data = sanitize_array(data, index, dtype, copy) 

511 data = SingleBlockManager.from_array(data, index, refs=refs) 

512 

513 NDFrame.__init__(self, data) 

514 self.name = name 

515 self._set_axis(0, index) 

516 

517 def _init_dict( 

518 self, data: Mapping, index: Index | None = None, dtype: DtypeObj | None = None 

519 ): 

520 """ 

521 Derive the "_mgr" and "index" attributes of a new Series from a 

522 dictionary input. 

523 

524 Parameters 

525 ---------- 

526 data : dict or dict-like 

527 Data used to populate the new Series. 

528 index : Index or None, default None 

529 Index for the new Series: if None, use dict keys. 

530 dtype : np.dtype, ExtensionDtype, or None, default None 

531 The dtype for the new Series: if None, infer from data. 

532 

533 Returns 

534 ------- 

535 _data : BlockManager for the new Series 

536 index : index for the new Series 

537 """ 

538 # Looking for NaN in dict doesn't work ({np.nan : 1}[float('nan')] 

539 # raises KeyError), so we iterate the entire dict, and align 

540 if data: 

541 # GH:34717, issue was using zip to extract key and values from data. 

542 # using generators in effects the performance. 

543 # Below is the new way of extracting the keys and values 

544 

545 keys = maybe_sequence_to_range(tuple(data.keys())) 

546 values = list(data.values()) # Generating list of values- faster way 

547 elif index is not None: 

548 # fastpath for Series(data=None). Just use broadcasting a scalar 

549 # instead of reindexing. 

550 if len(index) or dtype is not None: 

551 na_value = na_value_for_dtype(pandas_dtype(dtype), compat=False) 

552 # GH#33900, GH#41377 na_value may itself be dict-like (e.g. for a 

553 # nested ExtensionDtype), so broadcast it here rather than passing 

554 # it back through the Series constructor, which would route it to 

555 # _init_dict again and recurse. 

556 arr = construct_1d_arraylike_from_scalar(na_value, len(index), dtype) 

557 return SingleBlockManager.from_array(arr, index), index 

558 values = [] 

559 keys = index 

560 else: 

561 keys, values = default_index(0), [] 

562 

563 # Input is now list-like, so rely on "standard" construction: 

564 s = Series(values, index=keys, dtype=dtype) 

565 

566 # Now we just make sure the order is respected, if any 

567 if data and index is not None: 

568 s = s.reindex(index) 

569 return s._mgr, s.index 

570 

571 # ---------------------------------------------------------------------- 

572 

573 def __arrow_c_stream__(self, requested_schema=None): 

574 """ 

575 Export the pandas Series as an Arrow C stream PyCapsule. 

576 

577 This relies on pyarrow to convert the pandas Series to the Arrow 

578 format (and follows the default behavior of ``pyarrow.Array.from_pandas`` 

579 in its handling of the index, i.e. to ignore it). 

580 This conversion is not necessarily zero-copy. 

581 

582 Parameters 

583 ---------- 

584 requested_schema : PyCapsule, default None 

585 The schema to which the dataframe should be casted, passed as a 

586 PyCapsule containing a C ArrowSchema representation of the 

587 requested schema. 

588 

589 Returns 

590 ------- 

591 PyCapsule 

592 """ 

593 pa = import_optional_dependency("pyarrow", min_version="16.0.0") 

594 type = ( 

595 pa.DataType._import_from_c_capsule(requested_schema) 

596 if requested_schema is not None 

597 else None 

598 ) 

599 with suppress_pyarrow_values_warning(): 

600 ca = pa.array(self, type=type) 

601 if not isinstance(ca, pa.ChunkedArray): 

602 ca = pa.chunked_array([ca]) 

603 return ca.__arrow_c_stream__() 

604 

605 # ---------------------------------------------------------------------- 

606 

607 @property 

608 def _constructor(self) -> type[Series]: 

609 return Series 

610 

611 def _constructor_from_mgr(self, mgr, axes): 

612 ser = Series._from_mgr(mgr, axes=axes) 

613 # Use object.__setattr__ to bypass NDFrame.__setattr__ overhead. 

614 # _name is not set by NDFrame.__init__, so we initialize it here. 

615 object.__setattr__(ser, "_name", None) 

616 

617 if type(self) is Series: 

618 # This would also work `if self._constructor is Series`, but 

619 # this check is slightly faster, benefiting the most-common case. 

620 return ser 

621 

622 # We assume that the subclass __init__ knows how to handle a 

623 # pd.Series object. 

624 return self._constructor(ser) 

625 

626 @property 

627 def _constructor_expanddim(self) -> Callable[..., DataFrame]: 

628 """ 

629 Used when a manipulation result has one higher dimension as the 

630 original, such as Series.to_frame() 

631 """ 

632 from pandas.core.frame import DataFrame 

633 

634 return DataFrame 

635 

636 def _constructor_expanddim_from_mgr(self, mgr, axes): 

637 from pandas.core.frame import DataFrame 

638 

639 df = DataFrame._from_mgr(mgr, axes=mgr.axes) 

640 

641 if type(self) is Series: 

642 # This would also work `if self._constructor_expanddim is DataFrame`, 

643 # but this check is slightly faster, benefiting the most-common case. 

644 return df 

645 

646 # We assume that the subclass __init__ knows how to handle a 

647 # pd.DataFrame object. 

648 return self._constructor_expanddim(df) 

649 

650 # types 

651 @property 

652 def _can_hold_na(self) -> bool: 

653 return self._mgr._can_hold_na 

654 

655 # ndarray compatibility 

656 @property 

657 def dtype(self) -> DtypeObj: 

658 """ 

659 Return the dtype object of the underlying data. 

660 

661 This is the dtype of the array backing the Series (or the single dtype 

662 for a DataFrame column). For extension types, it returns the 

663 corresponding extension dtype. 

664 

665 See Also 

666 -------- 

667 Series.dtypes : Return the dtype object of the underlying data. 

668 Series.astype : Cast a pandas object to a specified dtype dtype. 

669 Series.convert_dtypes : Convert columns to the best possible dtypes using dtypes 

670 supporting pd.NA. 

671 

672 Examples 

673 -------- 

674 >>> s = pd.Series([1, 2, 3]) 

675 >>> s.dtype 

676 dtype('int64') 

677 """ 

678 return self._mgr.dtype 

679 

680 @property 

681 def dtypes(self) -> DtypeObj: 

682 """ 

683 Return the dtype object of the underlying data. 

684 

685 Unlike ``DataFrame.dtypes``, which returns a Series of dtypes for each 

686 column, ``Series.dtypes`` returns a single dtype object representing 

687 the type of all elements in the Series. 

688 

689 See Also 

690 -------- 

691 DataFrame.dtypes : Return the dtypes in the DataFrame. 

692 

693 Examples 

694 -------- 

695 >>> s = pd.Series([1, 2, 3]) 

696 >>> s.dtypes 

697 dtype('int64') 

698 """ 

699 # DataFrame compatibility 

700 return self.dtype 

701 

702 @property 

703 def name(self) -> Hashable: 

704 """ 

705 Return the name of the Series. 

706 

707 The name of a Series becomes its index or column name if it is used 

708 to form a DataFrame. It is also used whenever displaying the Series 

709 using the interpreter. 

710 

711 Returns 

712 ------- 

713 label (hashable object) 

714 The name of the Series, also the column name if part of a DataFrame. 

715 

716 See Also 

717 -------- 

718 Series.rename : Sets the Series name when given a scalar input. 

719 Index.name : Corresponding Index property. 

720 

721 Examples 

722 -------- 

723 The Series name can be set initially when calling the constructor. 

724 

725 >>> s = pd.Series([1, 2, 3], dtype=np.int64, name="Numbers") 

726 >>> s 

727 0 1 

728 1 2 

729 2 3 

730 Name: Numbers, dtype: int64 

731 >>> s.name = "Integers" 

732 >>> s 

733 0 1 

734 1 2 

735 2 3 

736 Name: Integers, dtype: int64 

737 

738 The name of a Series within a DataFrame is its column name. 

739 

740 >>> df = pd.DataFrame( 

741 ... [[1, 2], [3, 4], [5, 6]], columns=["Odd Numbers", "Even Numbers"] 

742 ... ) 

743 >>> df 

744 Odd Numbers Even Numbers 

745 0 1 2 

746 1 3 4 

747 2 5 6 

748 >>> df["Even Numbers"].name 

749 'Even Numbers' 

750 """ 

751 return self._name 

752 

753 @name.setter 

754 def name(self, value: Hashable) -> None: 

755 validate_all_hashable(value, error_name=f"{type(self).__name__}.name") 

756 object.__setattr__(self, "_name", value) 

757 

758 @property 

759 def values(self): 

760 """ 

761 Return Series as ndarray or ndarray-like depending on the dtype. 

762 

763 .. warning:: 

764 

765 We recommend using :attr:`Series.array` or 

766 :meth:`Series.to_numpy`, depending on whether you need 

767 a reference to the underlying data or a NumPy array. 

768 The return type of ``.values`` depends on the dtype: it is a 

769 :class:`numpy.ndarray` for some dtypes (for example ``int64`` 

770 or ``float64``) and an 

771 :class:`~pandas.api.extensions.ExtensionArray` for others (for 

772 example ``category``, nullable ``Int64``, or string dtypes), 

773 which makes it harder to write code that works across dtypes. 

774 ``.values`` also converts timezone-aware datetimes to UTC and 

775 drops the timezone. :attr:`Series.array` always returns 

776 the underlying array as an 

777 :class:`~pandas.api.extensions.ExtensionArray`, and 

778 :meth:`Series.to_numpy` always returns a :class:`numpy.ndarray` 

779 and accepts ``dtype``, ``copy``, and ``na_value`` arguments to 

780 control the conversion. 

781 

782 Returns 

783 ------- 

784 numpy.ndarray or ndarray-like 

785 

786 See Also 

787 -------- 

788 Series.array : Reference to the underlying data. 

789 Series.to_numpy : A NumPy array representing the underlying data. 

790 

791 Examples 

792 -------- 

793 For a Series backed by a NumPy dtype such as ``int64``, ``.values`` 

794 returns a :class:`numpy.ndarray`: 

795 

796 >>> pd.Series([1, 2, 3]).values 

797 array([1, 2, 3]) 

798 

799 For extension dtypes such as the default string dtype or 

800 ``category``, ``.values`` returns an 

801 :class:`~pandas.api.extensions.ExtensionArray` instead, while 

802 :meth:`Series.to_numpy` always returns a :class:`numpy.ndarray`: 

803 

804 >>> pd.Series(list("aabc")).values 

805 <ArrowStringArray> 

806 ['a', 'a', 'b', 'c'] 

807 Length: 4, dtype: str 

808 >>> pd.Series(list("aabc")).to_numpy() 

809 array(['a', 'a', 'b', 'c'], dtype=object) 

810 

811 >>> pd.Series(list("aabc")).astype("category").values 

812 ['a', 'a', 'b', 'c'] 

813 Categories (3, str): ['a', 'b', 'c'] 

814 

815 Timezone aware datetime data is converted to UTC and the timezone 

816 is dropped, while :attr:`Series.array` preserves the timezone: 

817 

818 >>> pd.Series( 

819 ... pd.date_range("20130101", periods=3, tz="US/Eastern") 

820 ... ).values # doctest: +SKIP 

821 array(['2013-01-01T05:00:00.000000', 

822 '2013-01-02T05:00:00.000000', 

823 '2013-01-03T05:00:00.000000'], dtype='datetime64[us]') 

824 >>> pd.Series(pd.date_range("20130101", periods=3, tz="US/Eastern")).array 

825 <DatetimeArray> 

826 ['2013-01-01 00:00:00-05:00', '2013-01-02 00:00:00-05:00', 

827 '2013-01-03 00:00:00-05:00'] 

828 Length: 3, dtype: datetime64[us, US/Eastern] 

829 

830 .. deprecated:: 3.0.0 

831 For :class:`DatetimeTZDtype`, :class:`PeriodDtype`, and 

832 :class:`IntervalDtype` dtypes, the behavior of ``.values`` returning 

833 a lossy or object-dtype result is deprecated. In a future version, 

834 ``.values`` will return the underlying ExtensionArray. Use 

835 :meth:`Series.to_numpy` or :attr:`Series.array` instead. 

836 """ 

837 if isinstance(self.dtype, (PeriodDtype, IntervalDtype)): 

838 warnings.warn( 

839 f"Series.values returning an object-dtype ndarray for " 

840 f"{type(self.dtype).__name__} dtype is deprecated. " 

841 f"In a future version, this will return the underlying " 

842 f"ExtensionArray instead. Use 'Series.to_numpy()' to get a " 

843 f"NumPy array, or 'Series.array' to get the ExtensionArray.", 

844 Pandas4Warning, 

845 stacklevel=2, 

846 ) 

847 elif isinstance(self.dtype, DatetimeTZDtype): 

848 warnings.warn( 

849 "Series.values returning an ndarray that drops timezone " 

850 "information for DatetimeTZDtype is deprecated. " 

851 "In a future version, this will return the underlying " 

852 "DatetimeArray instead. Use 'Series.dt.tz_convert(None).to_numpy()' " 

853 "to get a NumPy array of UTC values, or 'Series.array' to get the " 

854 "ExtensionArray.\n" 

855 "See https://pandas.pydata.org/docs/dev/whatsnew/v3.1.0.html#whatsnew-310-deprecations-values" 

856 " for more details.", 

857 Pandas4Warning, 

858 # TODO bump this to stacklevel=2 in a future version 

859 stacklevel=1, 

860 ) 

861 return self._mgr.external_values() 

862 

863 @property 

864 def _values(self): 

865 """ 

866 Return the internal repr of this data (defined by Block.interval_values). 

867 This are the values as stored in the Block (ndarray or ExtensionArray 

868 depending on the Block class), with datetime64[ns] and timedelta64[ns] 

869 wrapped in ExtensionArrays to match Index._values behavior. 

870 

871 Differs from the public ``.values`` for certain data types, because of 

872 historical backwards compatibility of the public attribute (e.g. period 

873 returns object ndarray and datetimetz a datetime64[ns] ndarray for 

874 ``.values`` while it returns an ExtensionArray for ``._values`` in those 

875 cases). This difference is deprecated and will be removed in a future 

876 version. 

877 

878 Differs from ``.array`` in that this still returns the numpy array if 

879 the Block is backed by a numpy array (except for datetime64 and 

880 timedelta64 dtypes), while ``.array`` ensures to always return an 

881 ExtensionArray. 

882 

883 Overview: 

884 

885 dtype | values | _values | array | 

886 ----------- | ------------- | ------------- | --------------------- | 

887 Numeric | ndarray | ndarray | NumpyExtensionArray | 

888 Category | Categorical | Categorical | Categorical | 

889 dt64[ns] | ndarray[M8ns] | DatetimeArray | DatetimeArray | 

890 dt64[ns tz] | ndarray[M8ns] | DatetimeArray | DatetimeArray | 

891 td64[ns] | ndarray[m8ns] | TimedeltaArray| TimedeltaArray | 

892 Period | ndarray[obj] | PeriodArray | PeriodArray | 

893 Nullable | EA | EA | EA | 

894 

895 """ 

896 return self._mgr.internal_values() 

897 

898 @property 

899 def _references(self) -> BlockValuesRefs: 

900 return self._mgr._block.refs 

901 

902 @property 

903 def array(self) -> ExtensionArray: 

904 """ 

905 The ExtensionArray of the data backing this Series or Index. 

906 

907 This property provides direct access to the underlying array data of a 

908 Series or Index without requiring conversion to a NumPy array. It 

909 returns an ExtensionArray, which is the native storage format for 

910 pandas extension dtypes. 

911 

912 Returns 

913 ------- 

914 ExtensionArray 

915 An ExtensionArray of the values stored within. For extension 

916 types, this is the actual array. For NumPy native types, this 

917 is a thin (no copy) wrapper around :class:`numpy.ndarray`. 

918 

919 ``.array`` differs from ``.values``, which may require converting 

920 the data to a different form. 

921 

922 See Also 

923 -------- 

924 Index.to_numpy : Similar method that always returns a NumPy array. 

925 Series.to_numpy : Similar method that always returns a NumPy array. 

926 

927 Notes 

928 ----- 

929 This table lays out the different array types for each extension 

930 dtype within pandas. 

931 

932 ================== ============================= 

933 dtype array type 

934 ================== ============================= 

935 category Categorical 

936 period PeriodArray 

937 interval IntervalArray 

938 IntegerNA IntegerArray 

939 string StringArray 

940 boolean BooleanArray 

941 datetime64[ns, tz] DatetimeArray 

942 ================== ============================= 

943 

944 For any 3rd-party extension types, the array type will be an 

945 ExtensionArray. 

946 

947 For all remaining dtypes ``.array`` will be a 

948 :class:`arrays.NumpyExtensionArray` wrapping the actual ndarray 

949 stored within. If you absolutely need a NumPy array (possibly with 

950 copying / coercing data), then use :meth:`Series.to_numpy` instead. 

951 

952 Examples 

953 -------- 

954 For regular NumPy types like int, and float, a NumpyExtensionArray 

955 is returned. 

956 

957 >>> pd.Series([1, 2, 3]).array 

958 <NumpyExtensionArray> 

959 [1, 2, 3] 

960 Length: 3, dtype: int64 

961 

962 For extension types, like Categorical, the actual ExtensionArray 

963 is returned 

964 

965 >>> ser = pd.Series(pd.Categorical(["a", "b", "a"])) 

966 >>> ser.array 

967 ['a', 'b', 'a'] 

968 Categories (2, str): ['a', 'b'] 

969 """ 

970 arr = self._mgr.array_values() 

971 # TODO decide on read-only https://github.com/pandas-dev/pandas/issues/63099 

972 # arr = arr.view() 

973 # arr._readonly = True 

974 return arr 

975 

976 def __len__(self) -> int: 

977 """ 

978 Return the length of the Series. 

979 """ 

980 return len(self._mgr) 

981 

982 # ---------------------------------------------------------------------- 

983 # NDArray Compat 

984 def __array__( 

985 self, dtype: npt.DTypeLike | None = None, copy: bool | None = None 

986 ) -> np.ndarray: 

987 """ 

988 Return the values as a NumPy array. 

989 

990 Users should not call this directly. Rather, it is invoked by 

991 :func:`numpy.array` and :func:`numpy.asarray`. 

992 

993 Parameters 

994 ---------- 

995 dtype : str or numpy.dtype, optional 

996 The dtype to use for the resulting NumPy array. By default, 

997 the dtype is inferred from the data. 

998 

999 copy : bool or None, optional 

1000 See :func:`numpy.asarray`. 

1001 

1002 Returns 

1003 ------- 

1004 numpy.ndarray 

1005 The values in the series converted to a :class:`numpy.ndarray` 

1006 with the specified `dtype`. 

1007 

1008 See Also 

1009 -------- 

1010 array : Create a new array from data. 

1011 Series.array : Zero-copy view to the array backing the Series. 

1012 Series.to_numpy : Series method for similar behavior. 

1013 

1014 Examples 

1015 -------- 

1016 >>> ser = pd.Series([1, 2, 3]) 

1017 >>> np.asarray(ser) 

1018 array([1, 2, 3]) 

1019 

1020 For timezone-aware data, the timezones may be retained with 

1021 ``dtype='object'`` 

1022 

1023 >>> tzser = pd.Series(pd.date_range("2000", periods=2, tz="CET")) 

1024 >>> np.asarray(tzser, dtype="object") 

1025 array([Timestamp('2000-01-01 00:00:00+0100', tz='CET'), 

1026 Timestamp('2000-01-02 00:00:00+0100', tz='CET')], 

1027 dtype=object) 

1028 

1029 Or the values may be localized to UTC and the tzinfo discarded with 

1030 ``dtype='datetime64[ns]'`` 

1031 

1032 >>> np.asarray(tzser, dtype="datetime64[ns]") # doctest: +ELLIPSIS 

1033 array(['1999-12-31T23:00:00.000000000', ...], 

1034 dtype='datetime64[ns]') 

1035 """ 

1036 values = self._values 

1037 if copy is None: 

1038 # Note: branch avoids `copy=None` for NumPy 1.x support 

1039 arr = np.asarray(values, dtype=dtype) 

1040 else: 

1041 arr = np.array(values, dtype=dtype, copy=copy) 

1042 

1043 if copy is True: 

1044 return arr 

1045 if copy is False or astype_is_view(values.dtype, arr.dtype): 

1046 arr = arr.view() 

1047 arr.flags.writeable = False 

1048 return arr 

1049 

1050 # ---------------------------------------------------------------------- 

1051 

1052 # indexers 

1053 @property 

1054 def axes(self) -> list[Index]: 

1055 """ 

1056 Return a list of the row axis labels. 

1057 """ 

1058 return [self.index] 

1059 

1060 # ---------------------------------------------------------------------- 

1061 # Indexing Methods 

1062 

1063 def _ixs(self, i: int | np.integer, axis: AxisInt = 0) -> Any: 

1064 """ 

1065 Return the i-th value or values in the Series by location. 

1066 

1067 Parameters 

1068 ---------- 

1069 i : int 

1070 

1071 Returns 

1072 ------- 

1073 scalar 

1074 """ 

1075 values = self._values 

1076 return maybe_unbox_numpy_scalar(values[i], object_with_dtype=values) 

1077 

1078 def _slice( 

1079 self, slobj: slice, axis: AxisInt = 0, new_index: Index | None = None 

1080 ) -> Series: 

1081 # axis kwarg is retained for compat with NDFrame method 

1082 # _slice is *always* positional 

1083 mgr = self._mgr.get_slice(slobj, axis=axis, new_index=new_index) 

1084 out = self._constructor_from_mgr(mgr, axes=mgr.axes) 

1085 out._name = self._name 

1086 return out.__finalize__(self) 

1087 

1088 def __getitem__(self, key): 

1089 check_dict_or_set_indexers(key) 

1090 key = com.apply_if_callable(key, self) 

1091 

1092 if key is Ellipsis: 

1093 return self.copy(deep=False) 

1094 

1095 key_is_scalar = is_scalar(key) 

1096 if isinstance(key, (list, tuple)): 

1097 key = unpack_1tuple(key) 

1098 

1099 elif key_is_scalar: 

1100 # Note: GH#50617 in 3.0 we changed int key to always be treated as 

1101 # a label, matching DataFrame behavior. 

1102 return self._get_value(key) 

1103 

1104 # Convert generator to list before going through hashable part 

1105 # (We will iterate through the generator there to check for slices) 

1106 if is_iterator(key): 

1107 key = list(key) 

1108 

1109 if is_hashable(key, allow_slice=False): 

1110 # Otherwise index.get_value will raise InvalidIndexError 

1111 try: 

1112 # For labels that don't resolve as scalars like tuples and frozensets 

1113 result = self._get_value(key) 

1114 

1115 return result 

1116 

1117 except (KeyError, TypeError, InvalidIndexError): 

1118 # InvalidIndexError for e.g. generator 

1119 # see test_series_getitem_corner_generator 

1120 if isinstance(key, tuple) and isinstance(self.index, MultiIndex): 

1121 # We still have the corner case where a tuple is a key 

1122 # in the first level of our MultiIndex 

1123 return self._get_values_tuple(key) 

1124 

1125 if isinstance(key, slice): 

1126 # Do slice check before somewhat-costly is_bool_indexer 

1127 return self._getitem_slice(key) 

1128 

1129 if com.is_bool_indexer(key): 

1130 key = check_bool_indexer(self.index, key) 

1131 key = np.asarray(key, dtype=bool) 

1132 return self._get_rows_with_mask(key) 

1133 

1134 return self._get_with(key) 

1135 

1136 def _get_with(self, key): 

1137 # other: fancy integer or otherwise 

1138 if isinstance(key, ABCDataFrame): 

1139 raise TypeError( 

1140 "Indexing a Series with DataFrame is not " 

1141 "supported, use the appropriate DataFrame column" 

1142 ) 

1143 elif isinstance(key, tuple): 

1144 return self._get_values_tuple(key) 

1145 

1146 return self.loc[key] 

1147 

1148 def _get_values_tuple(self, key: tuple): 

1149 # mpl hackaround 

1150 if com.any_none(*key): 

1151 # mpl compat if we look up e.g. ser[:, np.newaxis]; 

1152 # see tests.series.timeseries.test_mpl_compat_hack 

1153 # the asarray is needed to avoid returning a 2D DatetimeArray 

1154 result = np.asarray(self._values[key]) 

1155 disallow_ndim_indexing(result) 

1156 return result 

1157 

1158 if not isinstance(self.index, MultiIndex): 

1159 raise KeyError("key of type tuple not found and not a MultiIndex") 

1160 

1161 # If key is contained, would have returned by now 

1162 indexer, new_index = self.index.get_loc_level(key) 

1163 new_ser = self._constructor(self._values[indexer], index=new_index, copy=False) 

1164 if isinstance(indexer, slice): 

1165 new_ser._mgr.add_references(self._mgr) 

1166 return new_ser.__finalize__(self) 

1167 

1168 def _get_rows_with_mask(self, indexer: npt.NDArray[np.bool_]) -> Series: 

1169 new_mgr = self._mgr.get_rows_with_mask(indexer) 

1170 return self._constructor_from_mgr(new_mgr, axes=new_mgr.axes).__finalize__(self) 

1171 

1172 def _get_value(self, label, takeable: bool = False): 

1173 """ 

1174 Quickly retrieve single value at passed index label. 

1175 

1176 Parameters 

1177 ---------- 

1178 label : object 

1179 takeable : interpret the index as indexers, default False 

1180 

1181 Returns 

1182 ------- 

1183 scalar value 

1184 """ 

1185 if takeable: 

1186 return self._ixs(label) 

1187 

1188 # Similar to Index.get_value, but we do not fall back to positional 

1189 loc = self.index.get_loc(label) 

1190 

1191 if is_integer(loc): 

1192 return self._ixs(loc) 

1193 

1194 if isinstance(self.index, MultiIndex): 

1195 mi = self.index 

1196 new_values = self._values[loc] 

1197 if len(new_values) == 1 and mi.nlevels == 1: 

1198 # If more than one level left, we can not return a scalar 

1199 return maybe_unbox_numpy_scalar( 

1200 new_values[0], object_with_dtype=new_values 

1201 ) 

1202 

1203 new_index = mi[loc] 

1204 new_index = maybe_droplevels(new_index, label) 

1205 new_ser = self._constructor( 

1206 new_values, index=new_index, name=self.name, copy=False 

1207 ) 

1208 if isinstance(loc, slice): 

1209 new_ser._mgr.add_references(self._mgr) 

1210 return new_ser.__finalize__(self) 

1211 

1212 else: 

1213 return self.iloc[loc] 

1214 

1215 def __setitem__(self, key, value) -> None: 

1216 if not CHAINED_WARNING_DISABLED: 

1217 # the cheaper opcode check is deliberately last: on Python 3.14 

1218 # a plain `df[col] = value` reaches the refcount check, and 

1219 # is_local_in_caller_frame already short-circuits it there 

1220 if ( 

1221 sys.getrefcount(self) <= REF_COUNT 

1222 and not com.is_local_in_caller_frame(self) 

1223 and com.is_setitem_syntax_in_caller_frame() 

1224 ): 

1225 warnings.warn( 

1226 _chained_assignment_msg, ChainedAssignmentError, stacklevel=2 

1227 ) 

1228 

1229 check_dict_or_set_indexers(key) 

1230 key = com.apply_if_callable(key, self) 

1231 

1232 if key is Ellipsis: 

1233 key = slice(None) 

1234 

1235 if isinstance(key, slice): 

1236 indexer = self.index._convert_slice_indexer(key, kind="getitem") 

1237 return self._set_values(indexer, value) 

1238 

1239 try: 

1240 self._set_with_engine(key, value) 

1241 except KeyError: 

1242 # We have a scalar (or for MultiIndex or object-dtype, scalar-like) 

1243 # key that is not present in self.index. 

1244 # GH#12862 adding a new key to the Series 

1245 self.loc[key] = value 

1246 

1247 except (TypeError, ValueError, LossySetitemError): 

1248 # The key was OK, but we cannot set the value losslessly 

1249 indexer = self.index.get_loc(key) # type: ignore[assignment] 

1250 self._set_values(indexer, value) 

1251 

1252 except InvalidIndexError as err: 

1253 if isinstance(key, tuple) and not isinstance(self.index, MultiIndex): 

1254 # cases with MultiIndex don't get here bc they raise KeyError 

1255 # e.g. test_basic_getitem_setitem_corner 

1256 raise KeyError( 

1257 "key of type tuple not found and not a MultiIndex" 

1258 ) from err 

1259 

1260 if com.is_bool_indexer(key): 

1261 key = check_bool_indexer(self.index, key) 

1262 key = np.asarray(key, dtype=bool) 

1263 

1264 if ( 

1265 is_list_like(value) 

1266 and len(value) != len(self) 

1267 and not isinstance(value, Series) 

1268 and not is_object_dtype(self.dtype) 

1269 ): 

1270 # Series will be reindexed to have matching length inside 

1271 # _where call below 

1272 # GH#44265 

1273 indexer = key.nonzero()[0] 

1274 self._set_values(indexer, value) 

1275 return 

1276 

1277 # otherwise with listlike other we interpret series[mask] = other 

1278 # as series[mask] = other[mask] 

1279 try: 

1280 self._where(~key, value, inplace=True) 

1281 except InvalidIndexError: 

1282 # test_where_dups 

1283 self.iloc[key] = value 

1284 return 

1285 

1286 else: 

1287 self._set_with(key, value) 

1288 

1289 def _set_with_engine(self, key, value) -> None: 

1290 loc = self.index.get_loc(key) 

1291 

1292 # this is equivalent to self._values[key] = value 

1293 self._mgr.setitem_inplace(loc, value) 

1294 

1295 def _set_with(self, key, value) -> None: 

1296 # We got here via exception-handling off of InvalidIndexError, so 

1297 # key should always be listlike at this point. 

1298 assert not isinstance(key, tuple) 

1299 

1300 if is_iterator(key): 

1301 # Without this, the call to infer_dtype will consume the generator 

1302 key = list(key) 

1303 

1304 self._set_labels(key, value) 

1305 

1306 def _set_labels(self, key, value) -> None: 

1307 key = com.asarray_tuplesafe(key) 

1308 indexer: np.ndarray = self.index.get_indexer(key) 

1309 mask = indexer == -1 

1310 if mask.any(): 

1311 raise KeyError(f"{key[mask]} not in index") 

1312 self._set_values(indexer, value) 

1313 

1314 def _set_values(self, key, value) -> None: 

1315 if isinstance(key, (Index, Series)): 

1316 key = key._values 

1317 

1318 self._mgr = self._mgr.setitem(indexer=key, value=value) 

1319 

1320 def _set_value(self, label, value, takeable: bool = False) -> None: 

1321 """ 

1322 Quickly set single value at passed label. 

1323 

1324 If label is not contained, a new object is created with the label 

1325 placed at the end of the result index. 

1326 

1327 Parameters 

1328 ---------- 

1329 label : object 

1330 Partial indexing with MultiIndex not allowed. 

1331 value : object 

1332 Scalar value. 

1333 takeable : interpret the index as indexers, default False 

1334 """ 

1335 if not takeable: 

1336 try: 

1337 loc = self.index.get_loc(label) 

1338 except KeyError: 

1339 # set using a non-recursive method 

1340 self.loc[label] = value 

1341 return 

1342 except InvalidIndexError as ii_err: 

1343 # GH#51866: get_loc raises InvalidIndexError when label is not 

1344 # a scalar (e.g. a boolean mask, array, or list). .at only 

1345 # supports scalar label access. 

1346 raise InvalidIndexError( 

1347 ".at-based indexing can only have scalar indexers; use .loc instead" 

1348 ) from ii_err 

1349 else: 

1350 loc = label 

1351 

1352 self._set_values(loc, value) 

1353 

1354 # ---------------------------------------------------------------------- 

1355 # Unsorted 

1356 

1357 def repeat(self, repeats: int | Sequence[int], axis: None = None) -> Series: 

1358 """ 

1359 Repeat elements of a Series. 

1360 

1361 Returns a new Series where each element of the current Series 

1362 is repeated consecutively a given number of times. 

1363 

1364 Parameters 

1365 ---------- 

1366 repeats : int or array of ints 

1367 The number of repetitions for each element. This should be a 

1368 non-negative integer. Repeating 0 times will return an empty 

1369 Series. 

1370 axis : None 

1371 Unused. Parameter needed for compatibility with DataFrame. 

1372 

1373 Returns 

1374 ------- 

1375 Series 

1376 Newly created Series with repeated elements. 

1377 

1378 See Also 

1379 -------- 

1380 Index.repeat : Equivalent function for Index. 

1381 numpy.repeat : Similar method for :class:`numpy.ndarray`. 

1382 

1383 Examples 

1384 -------- 

1385 >>> s = pd.Series(["a", "b", "c"]) 

1386 >>> s 

1387 0 a 

1388 1 b 

1389 2 c 

1390 dtype: str 

1391 >>> s.repeat(2) 

1392 0 a 

1393 0 a 

1394 1 b 

1395 1 b 

1396 2 c 

1397 2 c 

1398 dtype: str 

1399 >>> s.repeat([1, 2, 3]) 

1400 0 a 

1401 1 b 

1402 1 b 

1403 2 c 

1404 2 c 

1405 2 c 

1406 dtype: str 

1407 """ 

1408 nv.validate_repeat((), {"axis": axis}) 

1409 new_index = self.index.repeat(repeats) 

1410 new_values = self._values.repeat(repeats) 

1411 return self._constructor(new_values, index=new_index, copy=False).__finalize__( 

1412 self, method="repeat" 

1413 ) 

1414 

1415 @overload 

1416 def reset_index( 

1417 self, 

1418 level: IndexLabel = ..., 

1419 *, 

1420 drop: Literal[False] = ..., 

1421 name: Level = ..., 

1422 inplace: Literal[False] = ..., 

1423 allow_duplicates: bool = ..., 

1424 ) -> DataFrame: ... 

1425 

1426 @overload 

1427 def reset_index( 

1428 self, 

1429 level: IndexLabel = ..., 

1430 *, 

1431 drop: Literal[True], 

1432 name: Level = ..., 

1433 inplace: Literal[False] = ..., 

1434 allow_duplicates: bool = ..., 

1435 ) -> Series: ... 

1436 

1437 @overload 

1438 def reset_index( 

1439 self, 

1440 level: IndexLabel = ..., 

1441 *, 

1442 drop: bool = ..., 

1443 name: Level = ..., 

1444 inplace: Literal[True], 

1445 allow_duplicates: bool = ..., 

1446 ) -> None: ... 

1447 

1448 def reset_index( 

1449 self, 

1450 level: IndexLabel | None = None, 

1451 *, 

1452 drop: bool = False, 

1453 name: Level = lib.no_default, 

1454 inplace: bool | lib.NoDefault = lib.no_default, 

1455 allow_duplicates: bool = False, 

1456 ) -> DataFrame | Series | None: 

1457 """ 

1458 Generate a new DataFrame or Series with the index reset. 

1459 

1460 This is useful when the index needs to be treated as a column, or 

1461 when the index is meaningless and needs to be reset to the default 

1462 before another operation. 

1463 

1464 Parameters 

1465 ---------- 

1466 level : int, str, tuple, or list, default optional 

1467 For a Series with a MultiIndex, only remove the specified levels 

1468 from the index. Removes all levels by default. 

1469 drop : bool, default False 

1470 Just reset the index, without inserting it as a column in 

1471 the new DataFrame. 

1472 name : object, optional 

1473 The name to use for the column containing the original Series 

1474 values. Uses ``self.name`` by default. This argument is ignored 

1475 when `drop` is True. 

1476 inplace : bool, default False 

1477 Modify the Series in place (do not create a new object). 

1478 

1479 .. deprecated:: 3.1.0 

1480 

1481 This keyword is deprecated and will be removed in pandas 4.0. 

1482 See the `whatsnew note on PDEP-8 

1483 <https://pandas.pydata.org/docs/dev/whatsnew/v3.1.0.html#deprecation-inplace>`__ 

1484 for more details. 

1485 

1486 allow_duplicates : bool, default False 

1487 Allow duplicate column labels to be created. 

1488 

1489 Returns 

1490 ------- 

1491 Series or DataFrame or None 

1492 When `drop` is False (the default), a DataFrame is returned. 

1493 The newly created columns will come first in the DataFrame, 

1494 followed by the original Series values. 

1495 When `drop` is True, a `Series` is returned. 

1496 In either case, if ``inplace=True``, no value is returned. 

1497 

1498 See Also 

1499 -------- 

1500 DataFrame.reset_index: Analogous function for DataFrame. 

1501 

1502 Examples 

1503 -------- 

1504 >>> s = pd.Series( 

1505 ... [1, 2, 3, 4], 

1506 ... name="foo", 

1507 ... index=pd.Index(["a", "b", "c", "d"], name="idx"), 

1508 ... ) 

1509 

1510 Generate a DataFrame with default index. 

1511 

1512 >>> s.reset_index() 

1513 idx foo 

1514 0 a 1 

1515 1 b 2 

1516 2 c 3 

1517 3 d 4 

1518 

1519 To specify the name of the new column use `name`. 

1520 

1521 >>> s.reset_index(name="values") 

1522 idx values 

1523 0 a 1 

1524 1 b 2 

1525 2 c 3 

1526 3 d 4 

1527 

1528 To generate a new Series with the default set `drop` to True. 

1529 

1530 >>> s.reset_index(drop=True) 

1531 0 1 

1532 1 2 

1533 2 3 

1534 3 4 

1535 Name: foo, dtype: int64 

1536 

1537 The `level` parameter is interesting for Series with a multi-level 

1538 index. 

1539 

1540 >>> arrays = [ 

1541 ... np.array(["bar", "bar", "baz", "baz"]), 

1542 ... np.array(["one", "two", "one", "two"]), 

1543 ... ] 

1544 >>> s2 = pd.Series( 

1545 ... range(4), 

1546 ... name="foo", 

1547 ... index=pd.MultiIndex.from_arrays(arrays, names=["a", "b"]), 

1548 ... ) 

1549 

1550 To remove a specific level from the Index, use `level`. 

1551 

1552 >>> s2.reset_index(level="a") 

1553 a foo 

1554 b 

1555 one bar 0 

1556 two bar 1 

1557 one baz 2 

1558 two baz 3 

1559 

1560 If `level` is not set, all levels are removed from the Index. 

1561 

1562 >>> s2.reset_index() 

1563 a b foo 

1564 0 bar one 0 

1565 1 bar two 1 

1566 2 baz one 2 

1567 3 baz two 3 

1568 """ 

1569 inplace = self._check_inplace_deprecation(inplace, "reset_index") 

1570 inplace = validate_bool_kwarg(inplace, "inplace") 

1571 if drop: 

1572 new_index = default_index(len(self)) 

1573 if level is not None: 

1574 level_list: Sequence[Hashable] 

1575 if not isinstance(level, (tuple, list)): 

1576 level_list = [level] 

1577 else: 

1578 level_list = level 

1579 level_list = [self.index._get_level_number(lev) for lev in level_list] 

1580 if len(level_list) < self.index.nlevels: 

1581 new_index = self.index.droplevel(level_list) # type: ignore[assignment] 

1582 

1583 if inplace: 

1584 self.index = new_index 

1585 else: 

1586 new_ser = self.copy(deep=False) 

1587 new_ser.index = new_index 

1588 return new_ser.__finalize__(self, method="reset_index") 

1589 elif inplace: 

1590 raise TypeError( 

1591 "Cannot reset_index inplace on a Series to create a DataFrame" 

1592 ) 

1593 else: 

1594 if name is lib.no_default: 

1595 # For backwards compatibility, keep columns as [0] instead of 

1596 # [None] when self.name is None 

1597 if self.name is None: 

1598 name = 0 

1599 else: 

1600 name = self.name 

1601 

1602 df = self.to_frame(name) 

1603 return df.reset_index( 

1604 level=level, drop=drop, allow_duplicates=allow_duplicates 

1605 ) 

1606 return None 

1607 

1608 # ---------------------------------------------------------------------- 

1609 # Rendering Methods 

1610 

1611 def __repr__(self) -> str: 

1612 """ 

1613 Return a string representation for a particular Series. 

1614 """ 

1615 repr_params = fmt.get_series_repr_params() 

1616 return self.to_string(**repr_params) 

1617 

1618 @overload 

1619 def to_string( 

1620 self, 

1621 buf: None = ..., 

1622 *, 

1623 na_rep: str = ..., 

1624 float_format: str | None = ..., 

1625 header: bool = ..., 

1626 index: bool = ..., 

1627 length: bool = ..., 

1628 dtype=..., 

1629 name=..., 

1630 max_rows: int | None = ..., 

1631 min_rows: int | None = ..., 

1632 ) -> str: ... 

1633 

1634 @overload 

1635 def to_string( 

1636 self, 

1637 buf: FilePath | WriteBuffer[str], 

1638 *, 

1639 na_rep: str = ..., 

1640 float_format: str | None = ..., 

1641 header: bool = ..., 

1642 index: bool = ..., 

1643 length: bool = ..., 

1644 dtype=..., 

1645 name=..., 

1646 max_rows: int | None = ..., 

1647 min_rows: int | None = ..., 

1648 ) -> None: ... 

1649 

1650 @deprecate_nonkeyword_arguments( 

1651 Pandas4Warning, allowed_args=["self", "buf"], name="to_string" 

1652 ) 

1653 def to_string( 

1654 self, 

1655 buf: FilePath | WriteBuffer[str] | None = None, 

1656 na_rep: str = "NaN", 

1657 float_format: str | None = None, 

1658 header: bool = True, 

1659 index: bool = True, 

1660 length: bool = False, 

1661 dtype: bool = False, 

1662 name: bool = False, 

1663 max_rows: int | None = None, 

1664 min_rows: int | None = None, 

1665 ) -> str | None: 

1666 """ 

1667 Render a string representation of the Series. 

1668 

1669 Produces a human-readable text format of the Series, including 

1670 optional display of the index, data types, name, and length. 

1671 The output can be written to a buffer or returned as a string. 

1672 

1673 Parameters 

1674 ---------- 

1675 buf : StringIO-like, optional 

1676 Buffer to write to. 

1677 na_rep : str, default 'NaN' 

1678 String representation of NaN to use. 

1679 float_format : one-parameter function, optional 

1680 Formatter function to apply to columns' elements if they are 

1681 floats, default None. 

1682 header : bool, default True 

1683 Add the Series header (index name). 

1684 index : bool, default True 

1685 Add index (row) labels. 

1686 length : bool, default False 

1687 Add the Series length. 

1688 dtype : bool, default False 

1689 Add the Series dtype. 

1690 name : bool, default False 

1691 Add the Series name if not None. 

1692 max_rows : int, optional 

1693 Maximum number of rows to show before truncating. If None, show 

1694 all. 

1695 min_rows : int, optional 

1696 The number of rows to display in a truncated repr (when number 

1697 of rows is above `max_rows`). 

1698 

1699 Returns 

1700 ------- 

1701 str or None 

1702 String representation of Series if ``buf=None``, otherwise None. 

1703 

1704 See Also 

1705 -------- 

1706 Series.to_dict : Convert Series to dict object. 

1707 Series.to_frame : Convert Series to DataFrame object. 

1708 Series.to_markdown : Print Series in Markdown-friendly format. 

1709 Series.to_timestamp : Cast to DatetimeIndex of Timestamps. 

1710 

1711 Examples 

1712 -------- 

1713 >>> ser = pd.Series([1, 2, 3]).to_string() 

1714 >>> ser 

1715 '0 1\\n1 2\\n2 3' 

1716 """ 

1717 formatter = fmt.SeriesFormatter( 

1718 self, 

1719 name=name, 

1720 length=length, 

1721 header=header, 

1722 index=index, 

1723 dtype=dtype, 

1724 na_rep=na_rep, 

1725 float_format=float_format, 

1726 min_rows=min_rows, 

1727 max_rows=max_rows, 

1728 ) 

1729 result = formatter.to_string() 

1730 

1731 # catch contract violations 

1732 if not isinstance(result, str): 

1733 raise AssertionError( 

1734 "result must be of type str, type " 

1735 f"of result is {type(result).__name__!r}" 

1736 ) 

1737 

1738 if buf is None: 

1739 return result 

1740 elif hasattr(buf, "write"): 

1741 buf.write(result) 

1742 else: 

1743 with open(buf, "w", encoding="utf-8") as f: 

1744 f.write(result) 

1745 return None 

1746 

1747 @overload 

1748 def to_markdown( 

1749 self, 

1750 buf: None = ..., 

1751 *, 

1752 mode: str = ..., 

1753 index: bool = ..., 

1754 storage_options: StorageOptions | None = ..., 

1755 **kwargs, 

1756 ) -> str: ... 

1757 

1758 @overload 

1759 def to_markdown( 

1760 self, 

1761 buf: IO[str], 

1762 *, 

1763 mode: str = ..., 

1764 index: bool = ..., 

1765 storage_options: StorageOptions | None = ..., 

1766 **kwargs, 

1767 ) -> None: ... 

1768 

1769 @overload 

1770 def to_markdown( 

1771 self, 

1772 buf: IO[str] | None, 

1773 *, 

1774 mode: str = ..., 

1775 index: bool = ..., 

1776 storage_options: StorageOptions | None = ..., 

1777 **kwargs, 

1778 ) -> str | None: ... 

1779 

1780 @deprecate_nonkeyword_arguments( 

1781 Pandas4Warning, allowed_args=["self", "buf"], name="to_markdown" 

1782 ) 

1783 def to_markdown( 

1784 self, 

1785 buf: IO[str] | None = None, 

1786 mode: str = "wt", 

1787 index: bool = True, 

1788 storage_options: StorageOptions | None = None, 

1789 **kwargs, 

1790 ) -> str | None: 

1791 """ 

1792 Print Series in Markdown-friendly format. 

1793 

1794 Converts the Series to a Markdown table representation using the 

1795 `tabulate <https://pypi.org/project/tabulate>`_ package. The output 

1796 can be written to a buffer or returned as a string. 

1797 

1798 Parameters 

1799 ---------- 

1800 buf : str, Path or StringIO-like, optional, default None 

1801 Buffer to write to. If None, the output is returned as a string. 

1802 mode : str, optional 

1803 Mode in which file is opened, "wt" by default. 

1804 index : bool, optional, default True 

1805 Add index (row) labels. 

1806 

1807 storage_options : dict, optional 

1808 Extra options that make sense for a particular storage connection, e.g. 

1809 host, port, username, password, etc. For HTTP(S) URLs the key-value pairs 

1810 are forwarded to ``urllib.request.Request`` as header options. For other 

1811 URLs (e.g. starting with "s3://", and "gcs://") the key-value pairs are 

1812 forwarded to ``fsspec.open``. Please see ``fsspec`` and ``urllib`` for more 

1813 details, and for more examples on storage options refer `here 

1814 <https://pandas.pydata.org/docs/user_guide/io.html? 

1815 highlight=storage_options#reading-writing-remote-files>`_. 

1816 

1817 **kwargs 

1818 These parameters will be passed to `tabulate \ 

1819 <https://pypi.org/project/tabulate>`_. 

1820 

1821 Returns 

1822 ------- 

1823 str 

1824 Series in Markdown-friendly format. 

1825 

1826 See Also 

1827 -------- 

1828 Series.to_frame : Rrite a text representation of object to the system clipboard. 

1829 Series.to_latex : Render Series to LaTeX-formatted table. 

1830 

1831 Notes 

1832 ----- 

1833 Requires the `tabulate <https://pypi.org/project/tabulate>`_ package. 

1834 

1835 Examples 

1836 -------- 

1837 >>> s = pd.Series(["elk", "pig", "dog", "quetzal"], name="animal") 

1838 >>> print(s.to_markdown()) 

1839 | | animal | 

1840 |---:|:---------| 

1841 | 0 | elk | 

1842 | 1 | pig | 

1843 | 2 | dog | 

1844 | 3 | quetzal | 

1845 

1846 Output markdown with a tabulate option. 

1847 

1848 >>> print(s.to_markdown(tablefmt="grid")) 

1849 +----+----------+ 

1850 | | animal | 

1851 +====+==========+ 

1852 | 0 | elk | 

1853 +----+----------+ 

1854 | 1 | pig | 

1855 +----+----------+ 

1856 | 2 | dog | 

1857 +----+----------+ 

1858 | 3 | quetzal | 

1859 +----+----------+ 

1860 """ 

1861 return self.to_frame().to_markdown( 

1862 buf, mode=mode, index=index, storage_options=storage_options, **kwargs 

1863 ) 

1864 

1865 # ---------------------------------------------------------------------- 

1866 

1867 def items(self) -> Iterable[tuple[Hashable, Any]]: 

1868 """ 

1869 Lazily iterate over (index, value) tuples. 

1870 

1871 This method returns an iterable tuple (index, value). This is 

1872 convenient if you want to create a lazy iterator. 

1873 

1874 Returns 

1875 ------- 

1876 iterable 

1877 Iterable of tuples containing the (index, value) pairs from a 

1878 Series. 

1879 

1880 See Also 

1881 -------- 

1882 DataFrame.items : Iterate over (column name, Series) pairs. 

1883 DataFrame.iterrows : Iterate over DataFrame rows as (index, Series) pairs. 

1884 

1885 Examples 

1886 -------- 

1887 >>> s = pd.Series(["A", "B", "C"]) 

1888 >>> for index, value in s.items(): 

1889 ... print(f"Index : {index}, Value : {value}") 

1890 Index : 0, Value : A 

1891 Index : 1, Value : B 

1892 Index : 2, Value : C 

1893 """ 

1894 return zip(iter(self.index), iter(self), strict=True) 

1895 

1896 # ---------------------------------------------------------------------- 

1897 # Misc public methods 

1898 

1899 def keys(self) -> Index: 

1900 """ 

1901 Return alias for index. 

1902 

1903 This method provides dictionary-like compatibility by returning the 

1904 index of the Series, analogous to the keys of a dictionary. 

1905 

1906 Returns 

1907 ------- 

1908 Index 

1909 Index of the Series. 

1910 

1911 See Also 

1912 -------- 

1913 Series.index : The index (axis labels) of the Series. 

1914 

1915 Examples 

1916 -------- 

1917 >>> s = pd.Series([1, 2, 3], index=[0, 1, 2]) 

1918 >>> s.keys() 

1919 Index([0, 1, 2], dtype='int64') 

1920 """ 

1921 return self.index 

1922 

1923 @overload 

1924 def to_dict( 

1925 self, *, into: type[MutableMappingT] | MutableMappingT 

1926 ) -> MutableMappingT: ... 

1927 

1928 @overload 

1929 def to_dict(self, *, into: type[dict] = ...) -> dict: ... 

1930 

1931 # error: Incompatible default for argument "into" (default has type "type[ 

1932 # dict[Any, Any]]", argument has type "type[MutableMappingT] | MutableMappingT") 

1933 def to_dict( 

1934 self, 

1935 *, 

1936 into: type[MutableMappingT] | MutableMappingT = dict, # type: ignore[assignment] 

1937 ) -> MutableMappingT: 

1938 """ 

1939 Convert Series to {label -> value} dict or dict-like object. 

1940 

1941 The resulting dict-like object maps each index label to its 

1942 corresponding value. A custom ``MutableMapping`` subclass can 

1943 be specified via the ``into`` parameter. 

1944 

1945 Parameters 

1946 ---------- 

1947 into : class, default dict 

1948 The collections.abc.MutableMapping subclass to use as the return 

1949 object. Can be the actual class or an empty instance of the mapping 

1950 type you want. If you want a collections.defaultdict, you must 

1951 pass it initialized. 

1952 

1953 Returns 

1954 ------- 

1955 collections.abc.MutableMapping 

1956 Key-value representation of Series. 

1957 

1958 See Also 

1959 -------- 

1960 Series.to_list: Converts Series to a list of the values. 

1961 Series.to_numpy: Converts Series to NumPy ndarray. 

1962 Series.array: ExtensionArray of the data backing this Series. 

1963 

1964 Examples 

1965 -------- 

1966 >>> s = pd.Series([1, 2, 3, 4]) 

1967 >>> s.to_dict() 

1968 {0: 1, 1: 2, 2: 3, 3: 4} 

1969 >>> from collections import OrderedDict, defaultdict 

1970 >>> s.to_dict(into=OrderedDict) 

1971 OrderedDict({0: 1, 1: 2, 2: 3, 3: 4}) 

1972 >>> dd = defaultdict(list) 

1973 >>> s.to_dict(into=dd) 

1974 defaultdict(<class 'list'>, {0: 1, 1: 2, 2: 3, 3: 4}) 

1975 """ 

1976 # GH16122 

1977 into_c = com.standardize_mapping(into) 

1978 

1979 if is_object_dtype(self.dtype) or isinstance(self.dtype, ExtensionDtype): 

1980 return into_c((k, maybe_box_native(v)) for k, v in self.items()) 

1981 else: 

1982 # Not an object dtype => all types will be the same so let the default 

1983 # indexer return native python type 

1984 return into_c(self.items()) 

1985 

1986 def to_frame(self, name: Hashable = lib.no_default) -> DataFrame: 

1987 """ 

1988 Convert Series to DataFrame. 

1989 

1990 The resulting DataFrame contains a single column. The name of the 

1991 column can be set using the ``name`` parameter; otherwise it 

1992 defaults to the Series' name. 

1993 

1994 Parameters 

1995 ---------- 

1996 name : object, optional 

1997 The passed name should substitute for the series name (if it has 

1998 one). 

1999 

2000 Returns 

2001 ------- 

2002 DataFrame 

2003 DataFrame representation of Series. 

2004 

2005 See Also 

2006 -------- 

2007 Series.to_dict : Convert Series to dict object. 

2008 

2009 Examples 

2010 -------- 

2011 >>> s = pd.Series(["a", "b", "c"], name="vals") 

2012 >>> s.to_frame() 

2013 vals 

2014 0 a 

2015 1 b 

2016 2 c 

2017 """ 

2018 columns: Index 

2019 if name is lib.no_default: 

2020 name = self.name 

2021 if name is None: 

2022 # default to [0], same as we would get with DataFrame(self) 

2023 columns = default_index(1) 

2024 else: 

2025 columns = Index([name]) 

2026 else: 

2027 columns = Index([name]) 

2028 

2029 mgr = self._mgr.to_2d_mgr(columns) 

2030 df = self._constructor_expanddim_from_mgr(mgr, axes=mgr.axes) 

2031 return df.__finalize__(self, method="to_frame") 

2032 

2033 @classmethod 

2034 def from_arrow(cls, data: ArrowArrayExportable | ArrowStreamExportable) -> Series: 

2035 """ 

2036 Construct a Series from an array-like Arrow object. 

2037 

2038 This function accepts any Arrow-compatible array-like object implementing 

2039 the `Arrow PyCapsule Protocol`_ (i.e. having an ``__arrow_c_array__`` 

2040 or ``__arrow_c_stream__`` method). 

2041 

2042 This function currently relies on ``pyarrow`` to convert the object 

2043 in Arrow format to pandas. 

2044 

2045 .. _Arrow PyCapsule Protocol: https://arrow.apache.org/docs/format/CDataInterface/PyCapsuleInterface.html 

2046 

2047 .. versionadded:: 3.0 

2048 

2049 Parameters 

2050 ---------- 

2051 data : pyarrow.Array or Arrow-compatible object 

2052 Any array-like object implementing the Arrow PyCapsule Protocol 

2053 (i.e. has an ``__arrow_c_array__`` or ``__arrow_c_stream__`` 

2054 method). 

2055 

2056 Returns 

2057 ------- 

2058 Series 

2059 

2060 See Also 

2061 -------- 

2062 DataFrame.from_arrow : Construct a DataFrame from an Arrow object. 

2063 

2064 Examples 

2065 -------- 

2066 >>> import pyarrow as pa 

2067 >>> arrow_array = pa.array([1, 2, 3]) 

2068 >>> pd.Series.from_arrow(arrow_array) 

2069 0 1 

2070 1 2 

2071 2 3 

2072 dtype: int64 

2073 """ 

2074 pa = import_optional_dependency("pyarrow", min_version="14.0.0") 

2075 if not isinstance(data, (pa.Array, pa.ChunkedArray)): 

2076 if not ( 

2077 hasattr(data, "__arrow_c_array__") 

2078 or hasattr(data, "__arrow_c_stream__") 

2079 ): 

2080 # explicitly test this, because otherwise we would accept variour other 

2081 # input types through the pa.chunked_array(..) call 

2082 raise TypeError( 

2083 "Expected an Arrow-compatible array-like object (i.e. having an " 

2084 "'_arrow_c_array__' or '__arrow_c_stream__' method), got " 

2085 f"'{type(data).__name__}' instead." 

2086 ) 

2087 # using chunked_array() as it works for both arrays and streams 

2088 pa_array = pa.chunked_array(data) 

2089 else: 

2090 pa_array = data 

2091 

2092 ser = arrow_table_to_pandas(pa.table({"col": pa_array}))["col"] 

2093 

2094 # for pyarrow, preserve to_pandas() behaviour of using a field name 

2095 name = None 

2096 try: 

2097 name = pa_array._name 

2098 except AttributeError: 

2099 pass 

2100 ser.name = name 

2101 

2102 return ser 

2103 

2104 def _set_name(self, name, inplace: bool = False) -> Series: 

2105 """ 

2106 Set the Series name. 

2107 

2108 Parameters 

2109 ---------- 

2110 name : str 

2111 inplace : bool 

2112 Whether to modify `self` directly or return a copy. 

2113 """ 

2114 inplace = validate_bool_kwarg(inplace, "inplace") 

2115 ser = self if inplace else self.copy(deep=False) 

2116 ser.name = name 

2117 return ser 

2118 

2119 @deprecate_nonkeyword_arguments( 

2120 Pandas4Warning, allowed_args=["self", "by", "level"], name="groupby" 

2121 ) 

2122 def groupby( 

2123 self, 

2124 by=None, 

2125 level: IndexLabel | None = None, 

2126 as_index: bool = True, 

2127 sort: bool = True, 

2128 group_keys: bool = True, 

2129 observed: bool = True, 

2130 dropna: bool = True, 

2131 ) -> SeriesGroupBy: 

2132 """ 

2133 Group Series using a mapper or by a Series of columns. 

2134 

2135 A groupby operation involves some combination of splitting the 

2136 object, applying a function, and combining the results. This can be 

2137 used to group large amounts of data and compute operations on these 

2138 groups. 

2139 

2140 Parameters 

2141 ---------- 

2142 by : mapping, function, label, pd.Grouper or list of such 

2143 Used to determine the groups for the groupby. 

2144 If ``by`` is a function, it's called on each value of the object's 

2145 index. If a dict or Series is passed, the Series or dict VALUES 

2146 will be used to determine the groups (the Series' values are first 

2147 aligned; see ``.align()`` method). If a list or ndarray of the 

2148 same length as the Series is passed (see the `groupby user guide 

2149 <https://pandas.pydata.org/pandas-docs/stable/user_guide/groupby.html#splitting-an-object-into-groups>`_), 

2150 the values are used as-is to determine the groups. An index level 

2151 name may also be passed to group by a level of the Series' index. 

2152 Notice that a tuple is interpreted as a (single) key. 

2153 level : int, level name, or sequence of such, default None 

2154 If the axis is a MultiIndex (hierarchical), group by a particular 

2155 level or levels. Do not specify both ``by`` and ``level``. 

2156 as_index : bool, default True 

2157 Return object with group labels as the index. This argument is 

2158 retained for compatibility with :meth:`DataFrame.groupby` and has 

2159 no effect on Series. 

2160 sort : bool, default True 

2161 Sort group keys. Get better performance by turning this off. 

2162 Note this does not influence the order of observations within each 

2163 group. Groupby preserves the order of rows within each group. If False, 

2164 the groups will appear in the same order as they did in the original 

2165 Series. 

2166 This argument has no effect on filtrations (see the `filtrations in the user 

2167 guide 

2168 <https://pandas.pydata.org/docs/dev/user_guide/groupby.html#filtration>`_), 

2169 such as ``head()``, ``tail()``, ``nth()`` and in transformations 

2170 (see the `transformations in the user guide 

2171 <https://pandas.pydata.org/docs/dev/user_guide/groupby.html#transformation>`_). 

2172 

2173 .. versionchanged:: 2.0.0 

2174 

2175 Specifying ``sort=False`` with an ordered categorical grouper will no 

2176 longer sort the values. 

2177 

2178 group_keys : bool, default True 

2179 When calling apply and the ``by`` argument produces a like-indexed 

2180 (i.e. :ref:`a transform <groupby.transform>`) result, add group keys to 

2181 index to identify pieces. By default group keys are not included 

2182 when the result's index (and column) labels match the inputs, and 

2183 are included otherwise. 

2184 

2185 .. versionchanged:: 2.0.0 

2186 

2187 ``group_keys`` now defaults to ``True``. 

2188 

2189 observed : bool, default True 

2190 This only applies if any of the groupers are Categoricals. 

2191 If True: only show observed values for categorical groupers. 

2192 If False: show all values for categorical groupers. 

2193 

2194 .. versionchanged:: 3.0.0 

2195 

2196 The default value is now ``True``. 

2197 

2198 dropna : bool, default True 

2199 If True, and if group keys contain NA values, NA values together 

2200 with row/column will be dropped. 

2201 If False, NA values will also be treated as the key in groups. 

2202 

2203 Returns 

2204 ------- 

2205 pandas.api.typing.SeriesGroupBy 

2206 Returns a groupby object that contains information about the groups. 

2207 

2208 See Also 

2209 -------- 

2210 resample : Convenience method for frequency conversion and resampling 

2211 of time series. 

2212 

2213 Notes 

2214 ----- 

2215 See the `user guide 

2216 <https://pandas.pydata.org/docs/dev/user_guide/groupby.html>`__ for more 

2217 detailed usage and examples, including splitting an object into groups, 

2218 iterating through groups, selecting a group, aggregation, and more. 

2219 

2220 The implementation of groupby is hash-based, meaning in particular that 

2221 objects that compare as equal will be considered to be in the same group. 

2222 An exception to this is that pandas has special handling of NA values: 

2223 any NA values will be collapsed to a single group, regardless of how 

2224 they compare. See the user guide linked above for more details. 

2225 

2226 Examples 

2227 -------- 

2228 >>> ser = pd.Series( 

2229 ... [390.0, 350.0, 30.0, 20.0], 

2230 ... index=["Falcon", "Falcon", "Parrot", "Parrot"], 

2231 ... name="Max Speed", 

2232 ... ) 

2233 >>> ser 

2234 Falcon 390.0 

2235 Falcon 350.0 

2236 Parrot 30.0 

2237 Parrot 20.0 

2238 Name: Max Speed, dtype: float64 

2239 

2240 We can pass a list of values to group the Series data by custom labels: 

2241 

2242 >>> ser.groupby(["a", "b", "a", "b"]).mean() 

2243 a 210.0 

2244 b 185.0 

2245 Name: Max Speed, dtype: float64 

2246 

2247 Grouping by numeric labels yields similar results: 

2248 

2249 >>> ser.groupby([0, 1, 0, 1]).mean() 

2250 0 210.0 

2251 1 185.0 

2252 Name: Max Speed, dtype: float64 

2253 

2254 We can group by a level of the index: 

2255 

2256 >>> ser.groupby(level=0).mean() 

2257 Falcon 370.0 

2258 Parrot 25.0 

2259 Name: Max Speed, dtype: float64 

2260 

2261 We can group by a condition applied to the Series values: 

2262 

2263 >>> ser.groupby(ser > 100).mean() 

2264 Max Speed 

2265 False 25.0 

2266 True 370.0 

2267 Name: Max Speed, dtype: float64 

2268 

2269 **Grouping by Indexes** 

2270 

2271 We can groupby different levels of a hierarchical index 

2272 using the `level` parameter: 

2273 

2274 >>> arrays = [ 

2275 ... ["Falcon", "Falcon", "Parrot", "Parrot"], 

2276 ... ["Captive", "Wild", "Captive", "Wild"], 

2277 ... ] 

2278 >>> index = pd.MultiIndex.from_arrays(arrays, names=("Animal", "Type")) 

2279 >>> ser = pd.Series([390.0, 350.0, 30.0, 20.0], index=index, name="Max Speed") 

2280 >>> ser 

2281 Animal Type 

2282 Falcon Captive 390.0 

2283 Wild 350.0 

2284 Parrot Captive 30.0 

2285 Wild 20.0 

2286 Name: Max Speed, dtype: float64 

2287 

2288 >>> ser.groupby(level=0).mean() 

2289 Animal 

2290 Falcon 370.0 

2291 Parrot 25.0 

2292 Name: Max Speed, dtype: float64 

2293 

2294 We can also group by the 'Type' level of the hierarchical index 

2295 to get the mean speed for each type: 

2296 

2297 >>> ser.groupby(level="Type").mean() 

2298 Type 

2299 Captive 210.0 

2300 Wild 185.0 

2301 Name: Max Speed, dtype: float64 

2302 

2303 We can also choose to include `NA` in group keys or not by defining 

2304 `dropna` parameter, the default setting is `True`. 

2305 

2306 >>> ser = pd.Series([1, 2, 3, 3], index=["a", "a", "b", np.nan]) 

2307 >>> ser.groupby(level=0).sum() 

2308 a 3 

2309 b 3 

2310 dtype: int64 

2311 

2312 To include `NA` values in the group keys, set `dropna=False`: 

2313 

2314 >>> ser.groupby(level=0, dropna=False).sum() 

2315 a 3 

2316 b 3 

2317 NaN 3 

2318 dtype: int64 

2319 

2320 We can also group by a custom list with NaN values to handle 

2321 missing group labels: 

2322 

2323 >>> arrays = ["Falcon", "Falcon", "Parrot", "Parrot"] 

2324 >>> ser = pd.Series([390.0, 350.0, 30.0, 20.0], index=arrays, name="Max Speed") 

2325 >>> ser.groupby(["a", "b", "a", np.nan]).mean() 

2326 a 210.0 

2327 b 350.0 

2328 Name: Max Speed, dtype: float64 

2329 

2330 >>> ser.groupby(["a", "b", "a", np.nan], dropna=False).mean() 

2331 a 210.0 

2332 b 350.0 

2333 NaN 20.0 

2334 Name: Max Speed, dtype: float64 

2335 """ 

2336 from pandas.core.groupby.generic import SeriesGroupBy 

2337 

2338 if level is None and by is None: 

2339 raise TypeError("You have to supply one of 'by' and 'level'") 

2340 if not as_index: 

2341 raise TypeError("as_index=False only valid with DataFrame") 

2342 

2343 return SeriesGroupBy( 

2344 obj=self, 

2345 keys=by, 

2346 level=level, 

2347 as_index=as_index, 

2348 sort=sort, 

2349 group_keys=group_keys, 

2350 observed=observed, 

2351 dropna=dropna, 

2352 ) 

2353 

2354 # ---------------------------------------------------------------------- 

2355 # Statistics, overridden ndarray methods 

2356 

2357 # TODO: integrate bottleneck 

2358 def count(self) -> int: 

2359 """ 

2360 Return number of non-NA/null observations in the Series. 

2361 

2362 This method counts the number of elements that are not missing 

2363 (i.e., not NaN or None) in the Series. 

2364 

2365 Returns 

2366 ------- 

2367 int 

2368 Number of non-null values in the Series. 

2369 

2370 See Also 

2371 -------- 

2372 DataFrame.count : Count non-NA cells for each column or row. 

2373 

2374 Examples 

2375 -------- 

2376 >>> s = pd.Series([0.0, 1.0, np.nan]) 

2377 >>> s.count() 

2378 2 

2379 """ 

2380 return maybe_unbox_numpy_scalar(notna(self._values).sum().astype("int64")) 

2381 

2382 def mode(self, dropna: bool = True) -> Series: 

2383 """ 

2384 Return the mode(s) of the Series. 

2385 

2386 The mode is the value that appears most often. There can be multiple modes. 

2387 

2388 Always returns Series even if only one value is returned. 

2389 

2390 Parameters 

2391 ---------- 

2392 dropna : bool, default True 

2393 Don't consider counts of NaN/NaT. 

2394 

2395 Returns 

2396 ------- 

2397 Series 

2398 Modes of the Series in sorted order. 

2399 

2400 See Also 

2401 -------- 

2402 numpy.mode : Equivalent numpy function for computing median. 

2403 Series.sum : Sum of the values. 

2404 Series.median : Median of the values. 

2405 Series.std : Standard deviation of the values. 

2406 Series.var : Variance of the values. 

2407 Series.min : Minimum value. 

2408 Series.max : Maximum value. 

2409 

2410 Examples 

2411 -------- 

2412 >>> s = pd.Series([2, 4, 2, 2, 4, None]) 

2413 >>> s.mode() 

2414 0 2.0 

2415 dtype: float64 

2416 

2417 More than one mode: 

2418 

2419 >>> s = pd.Series([2, 4, 8, 2, 4, None]) 

2420 >>> s.mode() 

2421 0 2.0 

2422 1 4.0 

2423 dtype: float64 

2424 

2425 With and without considering null value: 

2426 

2427 >>> s = pd.Series([2, 4, None, None, 4, None]) 

2428 >>> s.mode(dropna=False) 

2429 0 NaN 

2430 dtype: float64 

2431 >>> s = pd.Series([2, 4, None, None, 4, None]) 

2432 >>> s.mode() 

2433 0 4.0 

2434 dtype: float64 

2435 """ 

2436 # TODO: Add option for bins like value_counts() 

2437 values = self._values 

2438 if isinstance(values, np.ndarray): 

2439 res_values, _ = algorithms.mode(values, dropna=dropna) 

2440 else: 

2441 res_values = values._mode(dropna=dropna) 

2442 

2443 # Ensure index is type stable (should always use int index) 

2444 return self._constructor( 

2445 res_values, 

2446 index=range(len(res_values)), 

2447 name=self.name, 

2448 copy=False, 

2449 dtype=self.dtype, 

2450 ).__finalize__(self, method="mode") 

2451 

2452 def unique(self) -> ArrayLike: 

2453 """ 

2454 Return unique values of Series object. 

2455 

2456 Uniques are returned in order of appearance. Hash table-based unique, 

2457 therefore does NOT sort. 

2458 

2459 Returns 

2460 ------- 

2461 ndarray or ExtensionArray 

2462 The unique values returned as a NumPy array. See Notes. 

2463 

2464 See Also 

2465 -------- 

2466 Series.drop_duplicates : Return Series with duplicate values removed. 

2467 unique : Top-level unique method for any 1-d array-like object. 

2468 Index.unique : Return Index with unique values from an Index object. 

2469 

2470 Notes 

2471 ----- 

2472 Returns the unique values as a NumPy array. In case of an 

2473 extension-array backed Series, a new 

2474 :class:`~api.extensions.ExtensionArray` of that type with just 

2475 the unique values is returned. This includes 

2476 

2477 * Categorical 

2478 * Period 

2479 * Datetime with Timezone 

2480 * Datetime without Timezone 

2481 * Timedelta 

2482 * Interval 

2483 * Sparse 

2484 * IntegerNA 

2485 * String 

2486 

2487 See Examples section. 

2488 

2489 Examples 

2490 -------- 

2491 >>> pd.Series([2, 1, 3, 3], name="A").unique() 

2492 array([2, 1, 3]) 

2493 

2494 >>> pd.Series([pd.Timestamp("2016-01-01") for _ in range(3)]).unique() 

2495 <DatetimeArray> 

2496 ['2016-01-01 00:00:00'] 

2497 Length: 1, dtype: datetime64[us] 

2498 

2499 >>> pd.Series( 

2500 ... [pd.Timestamp("2016-01-01", tz="US/Eastern") for _ in range(3)] 

2501 ... ).unique() 

2502 <DatetimeArray> 

2503 ['2016-01-01 00:00:00-05:00'] 

2504 Length: 1, dtype: datetime64[us, US/Eastern] 

2505 

2506 A Categorical will return categories in the order of 

2507 appearance and with the same dtype. 

2508 

2509 >>> pd.Series(pd.Categorical(list("baabc"))).unique() 

2510 ['b', 'a', 'c'] 

2511 Categories (3, str): ['a', 'b', 'c'] 

2512 >>> pd.Series( 

2513 ... pd.Categorical(list("baabc"), categories=list("abc"), ordered=True) 

2514 ... ).unique() 

2515 ['b', 'a', 'c'] 

2516 Categories (3, str): ['a' < 'b' < 'c'] 

2517 """ 

2518 return super().unique() 

2519 

2520 @overload 

2521 def drop_duplicates( 

2522 self, 

2523 *, 

2524 keep: DropKeep = ..., 

2525 inplace: Literal[False] = ..., 

2526 ignore_index: bool = ..., 

2527 ) -> Series: ... 

2528 

2529 @overload 

2530 def drop_duplicates( 

2531 self, *, keep: DropKeep = ..., inplace: Literal[True], ignore_index: bool = ... 

2532 ) -> None: ... 

2533 

2534 @overload 

2535 def drop_duplicates( 

2536 self, *, keep: DropKeep = ..., inplace: bool = ..., ignore_index: bool = ... 

2537 ) -> Series | None: ... 

2538 

2539 def drop_duplicates( 

2540 self, 

2541 *, 

2542 keep: DropKeep = "first", 

2543 inplace: bool | lib.NoDefault = lib.no_default, 

2544 ignore_index: bool = False, 

2545 ) -> Series | None: 

2546 """ 

2547 Return Series with duplicate values removed. 

2548 

2549 This method identifies and removes duplicate values from the Series, 

2550 keeping the first, last, or none of the duplicate occurrences based 

2551 on the ``keep`` parameter. 

2552 

2553 Parameters 

2554 ---------- 

2555 keep : {'first', 'last', ``False``}, default 'first' 

2556 Method to handle dropping duplicates: 

2557 

2558 - 'first' : Drop duplicates except for the first occurrence. 

2559 - 'last' : Drop duplicates except for the last occurrence. 

2560 - ``False`` : Drop all duplicates. 

2561 

2562 inplace : bool, default ``False`` 

2563 If ``True``, performs operation inplace and returns None. 

2564 

2565 .. deprecated:: 3.1.0 

2566 

2567 This keyword is deprecated and will be removed in pandas 4.0. 

2568 See the `whatsnew note on PDEP-8 

2569 <https://pandas.pydata.org/docs/dev/whatsnew/v3.1.0.html#deprecation-inplace>`__ 

2570 for more details. 

2571 

2572 ignore_index : bool, default ``False`` 

2573 If ``True``, the resulting axis will be labeled 0, 1, …, n - 1. 

2574 

2575 .. versionadded:: 2.0.0 

2576 

2577 Returns 

2578 ------- 

2579 Series or None 

2580 Series with duplicates dropped or None if ``inplace=True``. 

2581 

2582 See Also 

2583 -------- 

2584 Index.drop_duplicates : Equivalent method on Index. 

2585 DataFrame.drop_duplicates : Equivalent method on DataFrame. 

2586 Series.duplicated : Related method on Series, indicating duplicate 

2587 Series values. 

2588 Series.unique : Return unique values as an array. 

2589 Index.duplicated : Indicate duplicate index values. 

2590 

2591 Examples 

2592 -------- 

2593 Generate a Series with duplicated entries. 

2594 

2595 >>> s = pd.Series( 

2596 ... ["llama", "cow", "llama", "beetle", "llama", "hippo"], name="animal" 

2597 ... ) 

2598 >>> s 

2599 0 llama 

2600 1 cow 

2601 2 llama 

2602 3 beetle 

2603 4 llama 

2604 5 hippo 

2605 Name: animal, dtype: str 

2606 

2607 With the 'keep' parameter, the selection behavior of duplicated values 

2608 can be changed. The value 'first' keeps the first occurrence for each 

2609 set of duplicated entries. The default value of keep is 'first'. 

2610 

2611 >>> s.drop_duplicates() 

2612 0 llama 

2613 1 cow 

2614 3 beetle 

2615 5 hippo 

2616 Name: animal, dtype: str 

2617 

2618 The value 'last' for parameter 'keep' keeps the last occurrence for 

2619 each set of duplicated entries. 

2620 

2621 >>> s.drop_duplicates(keep="last") 

2622 1 cow 

2623 3 beetle 

2624 4 llama 

2625 5 hippo 

2626 Name: animal, dtype: str 

2627 

2628 The value ``False`` for parameter 'keep' discards all sets of 

2629 duplicated entries. 

2630 

2631 >>> s.drop_duplicates(keep=False) 

2632 1 cow 

2633 3 beetle 

2634 5 hippo 

2635 Name: animal, dtype: str 

2636 

2637 Only the values are considered, not the index. To drop entries with a 

2638 duplicate index label, use :meth:`Index.duplicated` with boolean 

2639 indexing. 

2640 

2641 >>> s.index = ["a", "b", "b", "c", "c", "d"] 

2642 >>> s[~s.index.duplicated(keep="first")] 

2643 a llama 

2644 b cow 

2645 c beetle 

2646 d hippo 

2647 Name: animal, dtype: str 

2648 """ 

2649 inplace = self._check_inplace_deprecation(inplace, "drop_duplicates") 

2650 inplace = validate_bool_kwarg(inplace, "inplace") 

2651 result = super().drop_duplicates(keep=keep) 

2652 

2653 if ignore_index: 

2654 result.index = default_index(len(result)) 

2655 

2656 if inplace: 

2657 self._update_inplace(result) 

2658 return None 

2659 else: 

2660 return result 

2661 

2662 def duplicated(self, keep: DropKeep = "first") -> Series: 

2663 """ 

2664 Indicate duplicate Series values. 

2665 

2666 Duplicated values are indicated as ``True`` values in the resulting 

2667 Series. Values are considered duplicated when the same value appears 

2668 more than once. Either all duplicated values, all except the first, or 

2669 all except the last occurrence of duplicated values can be indicated. 

2670 

2671 Parameters 

2672 ---------- 

2673 keep : {'first', 'last', False}, default 'first' 

2674 Method to handle dropping duplicates: 

2675 

2676 - 'first' : Mark duplicates as ``True`` except for the first 

2677 occurrence. 

2678 - 'last' : Mark duplicates as ``True`` except for the last 

2679 occurrence. 

2680 - ``False`` : Mark all duplicates as ``True``. 

2681 

2682 Returns 

2683 ------- 

2684 Series[bool] 

2685 Series indicating whether each value is a duplicated value 

2686 according to ``keep``. 

2687 

2688 See Also 

2689 -------- 

2690 Index.duplicated : Equivalent method on pandas.Index. 

2691 DataFrame.duplicated : Equivalent method on pandas.DataFrame. 

2692 Series.drop_duplicates : Remove duplicate values from Series. 

2693 

2694 Examples 

2695 -------- 

2696 By default, for each set of duplicated values, the first occurrence is 

2697 set on False and all others on True: 

2698 

2699 >>> animals = pd.Series(["llama", "cow", "llama", "beetle", "llama"]) 

2700 >>> animals.duplicated() 

2701 0 False 

2702 1 False 

2703 2 True 

2704 3 False 

2705 4 True 

2706 dtype: bool 

2707 

2708 which is equivalent to 

2709 

2710 >>> animals.duplicated(keep="first") 

2711 0 False 

2712 1 False 

2713 2 True 

2714 3 False 

2715 4 True 

2716 dtype: bool 

2717 

2718 By using 'last', the last occurrence of each set of duplicated values 

2719 is set on False and all others on True: 

2720 

2721 >>> animals.duplicated(keep="last") 

2722 0 True 

2723 1 False 

2724 2 True 

2725 3 False 

2726 4 False 

2727 dtype: bool 

2728 

2729 By setting keep on ``False``, all duplicates are True: 

2730 

2731 >>> animals.duplicated(keep=False) 

2732 0 True 

2733 1 False 

2734 2 True 

2735 3 False 

2736 4 True 

2737 dtype: bool 

2738 """ 

2739 res = self._duplicated(keep=keep) 

2740 result = self._constructor(res, index=self.index, copy=False) 

2741 return result.__finalize__(self, method="duplicated") 

2742 

2743 def idxmin(self, axis: Axis = 0, skipna: bool = True, *args, **kwargs) -> Hashable: 

2744 """ 

2745 Return the row label of the minimum value. 

2746 

2747 If multiple values equal the minimum, the first row label with that 

2748 value is returned. 

2749 

2750 Parameters 

2751 ---------- 

2752 axis : {0 or 'index'} 

2753 Unused. Parameter needed for compatibility with DataFrame. 

2754 skipna : bool, default True 

2755 Exclude NA/null values. If the entire Series is NA, or if ``skipna=False`` 

2756 and there is an NA value, this method will raise a ``ValueError``. 

2757 *args, **kwargs 

2758 Additional arguments and keywords have no effect but might be 

2759 accepted for compatibility with NumPy. 

2760 See :ref:`gotchas.numpy_kwargs` for more. 

2761 

2762 Returns 

2763 ------- 

2764 Index 

2765 Label of the minimum value. 

2766 

2767 Raises 

2768 ------ 

2769 ValueError 

2770 If the Series is empty. 

2771 

2772 See Also 

2773 -------- 

2774 numpy.argmin : Return indices of the minimum values 

2775 along the given axis. 

2776 DataFrame.idxmin : Return index of first occurrence of minimum 

2777 over requested axis. 

2778 Series.idxmax : Return index *label* of the first occurrence 

2779 of maximum of values. 

2780 

2781 Notes 

2782 ----- 

2783 This method is the Series version of ``ndarray.argmin``. This method 

2784 returns the label of the minimum, while ``ndarray.argmin`` returns 

2785 the position. To get the position, use ``series.values.argmin()``. 

2786 

2787 Examples 

2788 -------- 

2789 >>> s = pd.Series(data=[1, None, 4, 1], index=["A", "B", "C", "D"]) 

2790 >>> s 

2791 A 1.0 

2792 B NaN 

2793 C 4.0 

2794 D 1.0 

2795 dtype: float64 

2796 

2797 >>> s.idxmin() 

2798 'A' 

2799 """ 

2800 axis = self._get_axis_number(axis) 

2801 iloc = self.argmin(axis, skipna, *args, **kwargs) 

2802 return self.index[iloc] 

2803 

2804 def idxmax(self, axis: Axis = 0, skipna: bool = True, *args, **kwargs) -> Hashable: 

2805 """ 

2806 Return the row label of the maximum value. 

2807 

2808 If multiple values equal the maximum, the first row label with that 

2809 value is returned. 

2810 

2811 Parameters 

2812 ---------- 

2813 axis : {0 or 'index'} 

2814 Unused. Parameter needed for compatibility with DataFrame. 

2815 skipna : bool, default True 

2816 Exclude NA/null values. If the entire Series is NA, or if ``skipna=False`` 

2817 and there is an NA value, this method will raise a ``ValueError``. 

2818 *args, **kwargs 

2819 Additional arguments and keywords have no effect but might be 

2820 accepted for compatibility with NumPy. 

2821 See :ref:`gotchas.numpy_kwargs` for more. 

2822 

2823 Returns 

2824 ------- 

2825 Index 

2826 Label of the maximum value. 

2827 

2828 Raises 

2829 ------ 

2830 ValueError 

2831 If the Series is empty. 

2832 

2833 See Also 

2834 -------- 

2835 numpy.argmax : Return indices of the maximum values 

2836 along the given axis. 

2837 DataFrame.idxmax : Return index of first occurrence of maximum 

2838 over requested axis. 

2839 Series.idxmin : Return index *label* of the first occurrence 

2840 of minimum of values. 

2841 

2842 Notes 

2843 ----- 

2844 This method is the Series version of ``ndarray.argmax``. This method 

2845 returns the label of the maximum, while ``ndarray.argmax`` returns 

2846 the position. To get the position, use ``series.values.argmax()``. 

2847 

2848 Examples 

2849 -------- 

2850 >>> s = pd.Series(data=[1, None, 4, 3, 4], index=["A", "B", "C", "D", "E"]) 

2851 >>> s 

2852 A 1.0 

2853 B NaN 

2854 C 4.0 

2855 D 3.0 

2856 E 4.0 

2857 dtype: float64 

2858 

2859 >>> s.idxmax() 

2860 'C' 

2861 """ 

2862 axis = self._get_axis_number(axis) 

2863 iloc = self.argmax(axis, skipna, *args, **kwargs) 

2864 return self.index[iloc] 

2865 

2866 def round(self, decimals: int = 0, *args, **kwargs) -> Series: 

2867 """ 

2868 Round each value in a Series to the given number of decimals. 

2869 

2870 This method returns a new Series with each element rounded to the 

2871 specified number of decimal places using the round-half-to-even 

2872 strategy. 

2873 

2874 Parameters 

2875 ---------- 

2876 decimals : int, default 0 

2877 Number of decimal places to round to. If decimals is negative, 

2878 it specifies the number of positions to the left of the decimal point. 

2879 *args, **kwargs 

2880 Additional arguments and keywords have no effect but might be 

2881 accepted for compatibility with NumPy. 

2882 See :ref:`gotchas.numpy_kwargs` for more. 

2883 

2884 Returns 

2885 ------- 

2886 Series 

2887 Rounded values of the Series. 

2888 

2889 See Also 

2890 -------- 

2891 numpy.around : Round values of an np.array. 

2892 DataFrame.round : Round values of a DataFrame. 

2893 Series.dt.round : Round values of data to the specified freq. 

2894 

2895 Notes 

2896 ----- 

2897 For values exactly halfway between rounded decimal values, pandas rounds 

2898 to the nearest even value (e.g. -0.5 and 0.5 round to 0.0, 1.5 and 2.5 

2899 round to 2.0, etc.). 

2900 

2901 Examples 

2902 -------- 

2903 >>> s = pd.Series([-0.5, 0.1, 2.5, 1.3, 2.7]) 

2904 >>> s.round() 

2905 0 -0.0 

2906 1 0.0 

2907 2 2.0 

2908 3 1.0 

2909 4 3.0 

2910 dtype: float64 

2911 """ 

2912 

2913 nv.validate_round(args, kwargs) 

2914 

2915 if len(self) == 0: 

2916 return self.copy() 

2917 

2918 if is_object_dtype(self.dtype): 

2919 values = self._values 

2920 result = lib.map_infer(values, lambda x: round(x, decimals), convert=False) 

2921 return self._constructor(result, index=self.index, copy=False).__finalize__( 

2922 self, method="round" 

2923 ) 

2924 new_mgr = self._mgr.round(decimals=decimals) 

2925 return self._constructor_from_mgr(new_mgr, axes=new_mgr.axes).__finalize__( 

2926 self, method="round" 

2927 ) 

2928 

2929 @overload 

2930 def quantile( 

2931 self, q: float = ..., interpolation: QuantileInterpolation = ... 

2932 ) -> float: ... 

2933 

2934 @overload 

2935 def quantile( 

2936 self, 

2937 q: Sequence[float] | AnyArrayLike, 

2938 interpolation: QuantileInterpolation = ..., 

2939 ) -> Series: ... 

2940 

2941 @overload 

2942 def quantile( 

2943 self, 

2944 q: float | Sequence[float] | AnyArrayLike = ..., 

2945 interpolation: QuantileInterpolation = ..., 

2946 ) -> float | Series: ... 

2947 

2948 def quantile( 

2949 self, 

2950 q: float | Sequence[float] | AnyArrayLike = 0.5, 

2951 interpolation: QuantileInterpolation = "linear", 

2952 ) -> float | Series: 

2953 """ 

2954 Return value at the given quantile. 

2955 

2956 This method computes the value below which a given fraction of the 

2957 data falls. When multiple quantiles are requested, a Series indexed 

2958 by the quantile values is returned. 

2959 

2960 Parameters 

2961 ---------- 

2962 q : float or array-like, default 0.5 (50% quantile) 

2963 The quantile(s) to compute, which can lie in range: 0 <= q <= 1. 

2964 interpolation : {'linear', 'lower', 'higher', 'midpoint', 'nearest'} 

2965 This optional parameter specifies the interpolation method to use, 

2966 when the desired quantile lies between two data points `i` and `j`: 

2967 

2968 * linear: `i + (j - i) * (x-i)/(j-i)`, where `(x-i)/(j-i)` is 

2969 the fractional part of the index surrounded by `i > j`. 

2970 * lower: `i`. 

2971 * higher: `j`. 

2972 * nearest: `i` or `j` whichever is nearest. 

2973 * midpoint: (`i` + `j`) / 2. 

2974 

2975 Returns 

2976 ------- 

2977 float or Series 

2978 If ``q`` is an array, a Series will be returned where the 

2979 index is ``q`` and the values are the quantiles, otherwise 

2980 a float will be returned. 

2981 

2982 See Also 

2983 -------- 

2984 core.window.Rolling.quantile : Calculate the rolling quantile. 

2985 numpy.percentile : Returns the q-th percentile(s) of the array elements. 

2986 

2987 Examples 

2988 -------- 

2989 >>> s = pd.Series([1, 2, 3, 4]) 

2990 >>> s.quantile(0.5) 

2991 2.5 

2992 >>> s.quantile([0.25, 0.5, 0.75]) 

2993 0.25 1.75 

2994 0.50 2.50 

2995 0.75 3.25 

2996 dtype: float64 

2997 """ 

2998 validate_percentile(q) 

2999 

3000 # We dispatch to DataFrame so that core.internals only has to worry 

3001 # about 2D cases. 

3002 df = self.to_frame() 

3003 

3004 result = df.quantile(q=q, interpolation=interpolation, numeric_only=False) 

3005 if result.ndim == 2: 

3006 result = result.iloc[:, 0] 

3007 

3008 if is_list_like(q): 

3009 result.name = self.name 

3010 idx = Index(q, dtype=np.float64) 

3011 return self._constructor(result, index=idx, name=self.name) 

3012 else: 

3013 # scalar 

3014 return result.iloc[0] 

3015 

3016 def corr( 

3017 self, 

3018 other: Series, 

3019 method: CorrelationMethod = "pearson", 

3020 min_periods: int | None = None, 

3021 ) -> float: 

3022 """ 

3023 Compute correlation with `other` Series, excluding missing values. 

3024 

3025 The two `Series` objects are not required to be the same length and will be 

3026 aligned internally before the correlation function is applied. 

3027 

3028 Parameters 

3029 ---------- 

3030 other : Series 

3031 Series with which to compute the correlation. 

3032 method : {'pearson', 'kendall', 'spearman'} or callable 

3033 Method used to compute correlation: 

3034 

3035 - pearson : Standard correlation coefficient 

3036 - kendall : Kendall Tau correlation coefficient 

3037 - spearman : Spearman rank correlation 

3038 - callable: Callable with input two 1d ndarrays and returning a float. 

3039 

3040 .. warning:: 

3041 Note that the returned matrix from corr will have 1 along the 

3042 diagonals and will be symmetric regardless of the callable's 

3043 behavior. 

3044 min_periods : int, optional 

3045 Minimum number of observations needed to have a valid result. 

3046 

3047 Returns 

3048 ------- 

3049 float 

3050 Correlation with other. 

3051 

3052 See Also 

3053 -------- 

3054 DataFrame.corr : Compute pairwise correlation between columns. 

3055 DataFrame.corrwith : Compute pairwise correlation with another 

3056 DataFrame or Series. 

3057 

3058 Notes 

3059 ----- 

3060 Pearson, Kendall and Spearman correlation are currently computed using pairwise complete observations. 

3061 

3062 * `Pearson correlation coefficient <https://en.wikipedia.org/wiki/Pearson_correlation_coefficient>`_ 

3063 * `Kendall rank correlation coefficient <https://en.wikipedia.org/wiki/Kendall_rank_correlation_coefficient>`_ 

3064 * `Spearman's rank correlation coefficient <https://en.wikipedia.org/wiki/Spearman%27s_rank_correlation_coefficient>`_ 

3065 

3066 Automatic data alignment: as with all pandas operations, automatic data alignment is performed for this method. 

3067 ``corr()`` automatically considers values with matching indices. 

3068 

3069 Examples 

3070 -------- 

3071 >>> def histogram_intersection(a, b): 

3072 ... v = np.minimum(a, b).sum().round(decimals=1) 

3073 ... return v 

3074 >>> s1 = pd.Series([0.2, 0.0, 0.6, 0.2]) 

3075 >>> s2 = pd.Series([0.3, 0.6, 0.0, 0.1]) 

3076 >>> s1.corr(s2, method=histogram_intersection) 

3077 0.3 

3078 

3079 Pandas auto-aligns the values with matching indices 

3080 

3081 >>> s1 = pd.Series([1, 2, 3], index=[0, 1, 2]) 

3082 >>> s2 = pd.Series([1, 2, 3], index=[2, 1, 0]) 

3083 >>> s1.corr(s2) 

3084 -1.0 

3085 

3086 If the input is a constant array, the correlation is not defined in this case, 

3087 and ``np.nan`` is returned. 

3088 

3089 >>> s1 = pd.Series([0.45, 0.45]) 

3090 >>> s1.corr(s1) 

3091 nan 

3092 """ # noqa: E501 

3093 this, other = self.align(other, join="inner") 

3094 if len(this) == 0: 

3095 return np.nan 

3096 

3097 this_values = this.to_numpy(dtype=float, na_value=np.nan, copy=False) 

3098 other_values = other.to_numpy(dtype=float, na_value=np.nan, copy=False) 

3099 

3100 if method in ["pearson", "spearman", "kendall"] or callable(method): 

3101 result = nanops.nancorr( 

3102 this_values, other_values, method=method, min_periods=min_periods 

3103 ) 

3104 result = maybe_unbox_numpy_scalar(result, object_with_dtype=self) 

3105 return result 

3106 

3107 raise ValueError( 

3108 "method must be either 'pearson', " 

3109 "'spearman', 'kendall', or a callable, " 

3110 f"'{method}' was supplied" 

3111 ) 

3112 

3113 def cov( 

3114 self, 

3115 other: Series, 

3116 min_periods: int | None = None, 

3117 ddof: int | None = 1, 

3118 ) -> float: 

3119 """ 

3120 Compute covariance with Series, excluding missing values. 

3121 

3122 The two `Series` objects are not required to be the same length and 

3123 will be aligned internally before the covariance is calculated. 

3124 

3125 Parameters 

3126 ---------- 

3127 other : Series 

3128 Series with which to compute the covariance. 

3129 min_periods : int, optional 

3130 Minimum number of observations needed to have a valid result. 

3131 ddof : int, default 1 

3132 Delta degrees of freedom. The divisor used in calculations 

3133 is ``N - ddof``, where ``N`` represents the number of elements. 

3134 

3135 Returns 

3136 ------- 

3137 float 

3138 Covariance between Series and other normalized by N-1 

3139 (unbiased estimator). 

3140 

3141 See Also 

3142 -------- 

3143 DataFrame.cov : Compute pairwise covariance of columns. 

3144 

3145 Examples 

3146 -------- 

3147 >>> s1 = pd.Series([0.90010907, 0.13484424, 0.62036035]) 

3148 >>> s2 = pd.Series([0.12528585, 0.26962463, 0.51111198]) 

3149 >>> s1.cov(s2) 

3150 -0.01685762652715874 

3151 """ 

3152 this, other = self.align(other, join="inner") 

3153 if len(this) == 0: 

3154 return np.nan 

3155 this_values = this.to_numpy(dtype=float, na_value=np.nan, copy=False) 

3156 other_values = other.to_numpy(dtype=float, na_value=np.nan, copy=False) 

3157 result = nanops.nancov( 

3158 this_values, other_values, min_periods=min_periods, ddof=ddof 

3159 ) 

3160 result = maybe_unbox_numpy_scalar(result, object_with_dtype=self) 

3161 return result 

3162 

3163 def describe( 

3164 self, 

3165 percentiles=None, 

3166 include=None, 

3167 exclude=None, 

3168 ) -> Series: 

3169 """ 

3170 Generate descriptive statistics. 

3171 

3172 Summarize the central tendency, dispersion, and shape of the 

3173 Series's distribution, excluding ``NaN`` values. The set of 

3174 statistics returned depends on the Series's dtype; see Notes. 

3175 

3176 Parameters 

3177 ---------- 

3178 percentiles : list-like of numbers, optional 

3179 The percentiles to include in the output. All should fall 

3180 between 0 and 1. The default, ``None``, returns the 25th, 

3181 50th, and 75th percentiles. 

3182 include : None 

3183 Has no effect on Series. Deprecated and will be removed in a 

3184 future version. 

3185 exclude : None 

3186 Has no effect on Series. Deprecated and will be removed in a 

3187 future version. 

3188 

3189 Returns 

3190 ------- 

3191 Series 

3192 Summary statistics of the Series. 

3193 

3194 See Also 

3195 -------- 

3196 DataFrame.describe : Generate descriptive statistics of a DataFrame. 

3197 Series.count : Count of non-NA observations. 

3198 Series.max : Maximum of the values. 

3199 Series.min : Minimum of the values. 

3200 Series.mean : Mean of the values. 

3201 Series.std : Standard deviation of the observations. 

3202 

3203 Notes 

3204 ----- 

3205 For numeric dtypes, the result's index includes ``count``, 

3206 ``mean``, ``std``, ``min``, ``max``, and the requested 

3207 percentiles. By default the lower percentile is ``25`` and the 

3208 upper is ``75``; the ``50`` percentile is the same as the median. 

3209 

3210 For object dtypes (e.g. strings), the result's index includes 

3211 ``count``, ``unique``, ``top``, and ``freq``. The ``top`` is the 

3212 most common value and ``freq`` is its count. If multiple values 

3213 tie for the highest count, ``top`` is chosen arbitrarily from 

3214 among them. 

3215 

3216 For datetime dtypes, the result also includes ``mean`` and the 

3217 requested percentiles, computed on the underlying timestamps. 

3218 

3219 Examples 

3220 -------- 

3221 A numeric Series. 

3222 

3223 >>> s = pd.Series([1, 2, 3]) 

3224 >>> s.describe() 

3225 count 3.0 

3226 mean 2.0 

3227 std 1.0 

3228 min 1.0 

3229 25% 1.5 

3230 50% 2.0 

3231 75% 2.5 

3232 max 3.0 

3233 dtype: float64 

3234 

3235 An object Series. 

3236 

3237 >>> s = pd.Series(["a", "a", "b", "c"]) 

3238 >>> s.describe() 

3239 count 4 

3240 unique 3 

3241 top a 

3242 freq 2 

3243 dtype: object 

3244 

3245 A datetime Series. 

3246 

3247 >>> s = pd.Series( 

3248 ... [ 

3249 ... np.datetime64("2000-01-01"), 

3250 ... np.datetime64("2010-01-01"), 

3251 ... np.datetime64("2010-01-01"), 

3252 ... ] 

3253 ... ) 

3254 >>> s.describe() 

3255 count 3 

3256 mean 2006-09-01 08:00:00 

3257 min 2000-01-01 00:00:00 

3258 25% 2004-12-31 12:00:00 

3259 50% 2010-01-01 00:00:00 

3260 75% 2010-01-01 00:00:00 

3261 max 2010-01-01 00:00:00 

3262 dtype: object 

3263 """ 

3264 return super().describe( 

3265 percentiles=percentiles, include=include, exclude=exclude 

3266 ) 

3267 

3268 def diff(self, periods: int = 1) -> Series: 

3269 """ 

3270 First discrete difference of Series elements. 

3271 

3272 Calculates the difference of a Series element compared with another 

3273 element in the Series (default is element in previous row). 

3274 

3275 Parameters 

3276 ---------- 

3277 periods : int, default 1 

3278 Periods to shift for calculating difference, accepts negative 

3279 values. 

3280 

3281 Returns 

3282 ------- 

3283 Series 

3284 First differences of the Series. 

3285 

3286 See Also 

3287 -------- 

3288 Series.pct_change: Percent change over given number of periods. 

3289 Series.shift: Shift index by desired number of periods with an 

3290 optional time freq. 

3291 DataFrame.diff: First discrete difference of object. 

3292 

3293 Notes 

3294 ----- 

3295 Equivalent to ``self - self.shift(periods)``, except that boolean 

3296 dtypes use :meth:`operator.xor` rather than :meth:`operator.sub`; the 

3297 result dtype follows from that operation. 

3298 

3299 In particular, because the leading ``periods`` positions are filled 

3300 with a missing value, NumPy integer dtypes are cast to floating and 

3301 NumPy ``bool`` to ``object``. 

3302 

3303 Examples 

3304 -------- 

3305 

3306 Difference with previous row 

3307 

3308 >>> s = pd.Series([1, 1, 2, 3, 5, 8]) 

3309 >>> s.diff() 

3310 0 NaN 

3311 1 0.0 

3312 2 1.0 

3313 3 1.0 

3314 4 2.0 

3315 5 3.0 

3316 dtype: float64 

3317 

3318 Difference with 3rd previous row 

3319 

3320 >>> s.diff(periods=3) 

3321 0 NaN 

3322 1 NaN 

3323 2 NaN 

3324 3 2.0 

3325 4 4.0 

3326 5 6.0 

3327 dtype: float64 

3328 

3329 Difference with following row 

3330 

3331 >>> s.diff(periods=-1) 

3332 0 0.0 

3333 1 -1.0 

3334 2 -1.0 

3335 3 -2.0 

3336 4 -3.0 

3337 5 NaN 

3338 dtype: float64 

3339 

3340 Overflow in input dtype 

3341 

3342 >>> s = pd.Series([1, 0], dtype=np.uint8) 

3343 >>> s.diff() 

3344 0 NaN 

3345 1 255.0 

3346 dtype: float64 

3347 """ 

3348 if not lib.is_integer(periods): 

3349 if not (is_float(periods) and periods.is_integer()): 

3350 raise ValueError("periods must be an integer") 

3351 result = algorithms.diff(self._values, periods) 

3352 return self._constructor( 

3353 result, index=self.index.view(), copy=False 

3354 ).__finalize__(self, method="diff") 

3355 

3356 def autocorr(self, lag: int = 1) -> float: 

3357 """ 

3358 Compute the lag-N autocorrelation. 

3359 

3360 This method computes the Pearson correlation between 

3361 the Series and its shifted self. 

3362 

3363 Parameters 

3364 ---------- 

3365 lag : int, default 1 

3366 Number of lags to apply before performing autocorrelation. 

3367 

3368 Returns 

3369 ------- 

3370 float 

3371 The Pearson correlation between self and self.shift(lag). 

3372 

3373 See Also 

3374 -------- 

3375 Series.corr : Compute the correlation between two Series. 

3376 Series.shift : Shift index by desired number of periods. 

3377 DataFrame.corr : Compute pairwise correlation of columns. 

3378 DataFrame.corrwith : Compute pairwise correlation between rows or 

3379 columns of two DataFrame objects. 

3380 

3381 Notes 

3382 ----- 

3383 If the Pearson correlation is not well defined return 'NaN'. 

3384 

3385 Examples 

3386 -------- 

3387 >>> s = pd.Series([0.25, 0.5, 0.2, -0.05]) 

3388 >>> s.autocorr() # doctest: +ELLIPSIS 

3389 0.10355... 

3390 >>> s.autocorr(lag=2) # doctest: +ELLIPSIS 

3391 -0.99999... 

3392 

3393 If the Pearson correlation is not well defined, then 'NaN' is returned. 

3394 

3395 >>> s = pd.Series([1, 0, 0, 0]) 

3396 >>> s.autocorr() 

3397 nan 

3398 """ 

3399 return self.corr(cast("Series", self.shift(lag))) 

3400 

3401 def dot(self, other: AnyArrayLike | DataFrame) -> Series | np.ndarray: 

3402 """ 

3403 Compute the dot product between the Series and the columns of other. 

3404 

3405 This method computes the dot product between the Series and another 

3406 one, or the Series and each columns of a DataFrame, or the Series and 

3407 each columns of an array. 

3408 

3409 It can also be called using `self @ other`. 

3410 

3411 Parameters 

3412 ---------- 

3413 other : Series, DataFrame or array-like 

3414 The other object to compute the dot product with its columns. 

3415 

3416 Returns 

3417 ------- 

3418 scalar, Series or numpy.ndarray 

3419 Return the dot product of the Series and other if other is a 

3420 Series, the Series of the dot product of Series and each rows of 

3421 other if other is a DataFrame or a numpy.ndarray between the Series 

3422 and each columns of the numpy array. 

3423 

3424 See Also 

3425 -------- 

3426 DataFrame.dot: Compute the matrix product with the DataFrame. 

3427 Series.mul: Multiplication of series and other, element-wise. 

3428 

3429 Notes 

3430 ----- 

3431 The Series and other has to share the same index if other is a Series 

3432 or a DataFrame. 

3433 

3434 Examples 

3435 -------- 

3436 >>> s = pd.Series([0, 1, 2, 3]) 

3437 >>> other = pd.Series([-1, 2, -3, 4]) 

3438 >>> s.dot(other) 

3439 8 

3440 >>> s @ other 

3441 8 

3442 >>> df = pd.DataFrame([[0, 1], [-2, 3], [4, -5], [6, 7]]) 

3443 >>> s.dot(df) 

3444 0 24 

3445 1 14 

3446 dtype: int64 

3447 >>> arr = np.array([[0, 1], [-2, 3], [4, -5], [6, 7]]) 

3448 >>> s.dot(arr) 

3449 array([24, 14]) 

3450 """ 

3451 if isinstance(other, (Series, ABCDataFrame)): 

3452 common = self.index.union(other.index) 

3453 if len(common) > len(self.index) or len(common) > len(other.index): 

3454 raise ValueError("matrices are not aligned") 

3455 

3456 left = self.reindex(index=common) 

3457 right = other.reindex(index=common) 

3458 lvals = left.values 

3459 rvals = right.values 

3460 else: 

3461 lvals = self.values 

3462 rvals = np.asarray(other) 

3463 if lvals.shape[0] != rvals.shape[0]: 

3464 raise Exception( 

3465 f"Dot product shape mismatch, {lvals.shape} vs {rvals.shape}" 

3466 ) 

3467 

3468 if isinstance(other, ABCDataFrame): 

3469 common_type = find_common_type([self.dtypes, *list(other.dtypes)]) 

3470 return self._constructor( 

3471 np.dot(lvals, rvals), index=other.columns, copy=False, dtype=common_type 

3472 ).__finalize__(self, method="dot") 

3473 elif isinstance(other, Series): 

3474 result = np.dot(lvals, rvals) 

3475 elif isinstance(rvals, np.ndarray): 

3476 result = np.dot(lvals, rvals) 

3477 else: # pragma: no cover 

3478 raise TypeError(f"unsupported type: {type(other)}") 

3479 return maybe_unbox_numpy_scalar(result, object_with_dtype=self) 

3480 

3481 def __matmul__(self, other): 

3482 """ 

3483 Matrix multiplication using binary `@` operator. 

3484 """ 

3485 return self.dot(other) 

3486 

3487 def __rmatmul__(self, other): 

3488 """ 

3489 Matrix multiplication using binary `@` operator. 

3490 """ 

3491 return self.dot(np.transpose(other)) 

3492 

3493 # Signature of "searchsorted" incompatible with supertype "IndexOpsMixin" 

3494 def searchsorted( # type: ignore[override] 

3495 self, 

3496 value: NumpyValueArrayLike | ExtensionArray, 

3497 side: Literal["left", "right"] = "left", 

3498 sorter: NumpySorter | None = None, 

3499 ) -> npt.NDArray[np.intp] | np.intp: 

3500 """ 

3501 Find indices where elements should be inserted to maintain order. 

3502 

3503 Find the indices into a sorted Series `self` such that, if the 

3504 corresponding elements in `value` were inserted before the indices, 

3505 the order of `self` would be preserved. 

3506 

3507 .. note:: 

3508 The Series *must* be monotonically sorted, otherwise 

3509 wrong locations will likely be returned. Pandas does *not* 

3510 check this for you. 

3511 

3512 Parameters 

3513 ---------- 

3514 value : array-like or scalar 

3515 Values to insert into `self`. 

3516 side : {'left', 'right'}, optional 

3517 If 'left', the index of the first suitable location found is given. 

3518 If 'right', return the last such index. If there is no suitable 

3519 index, return either 0 or N (where N is the length of `self`). 

3520 sorter : 1-D array-like, optional 

3521 Optional array of integer indices that sort `self` into ascending 

3522 order. They are typically the result of ``np.argsort``. 

3523 

3524 Returns 

3525 ------- 

3526 int or array of int 

3527 A scalar or array of insertion points with the 

3528 same shape as `value`. 

3529 

3530 See Also 

3531 -------- 

3532 sort_values : Sort by the values along either axis. 

3533 numpy.searchsorted : Similar method from NumPy. 

3534 

3535 Notes 

3536 ----- 

3537 Binary search is used to find the required insertion points. 

3538 

3539 Examples 

3540 -------- 

3541 >>> ser = pd.Series([1, 2, 3]) 

3542 >>> ser 

3543 0 1 

3544 1 2 

3545 2 3 

3546 dtype: int64 

3547 >>> ser.searchsorted(4) 

3548 3 

3549 >>> ser.searchsorted([0, 4]) 

3550 array([0, 3]) 

3551 >>> ser.searchsorted([1, 3], side="left") 

3552 array([0, 2]) 

3553 >>> ser.searchsorted([1, 3], side="right") 

3554 array([1, 3]) 

3555 >>> ser = pd.Series(pd.to_datetime(["3/11/2000", "3/12/2000", "3/13/2000"])) 

3556 >>> ser 

3557 0 2000-03-11 

3558 1 2000-03-12 

3559 2 2000-03-13 

3560 dtype: datetime64[us] 

3561 >>> ser.searchsorted("3/14/2000") 

3562 3 

3563 >>> ser = pd.Categorical( 

3564 ... ["apple", "bread", "bread", "cheese", "milk"], ordered=True 

3565 ... ) 

3566 >>> ser 

3567 ['apple', 'bread', 'bread', 'cheese', 'milk'] 

3568 Categories (4, str): ['apple' < 'bread' < 'cheese' < 'milk'] 

3569 >>> ser.searchsorted("bread") 

3570 np.int64(1) 

3571 >>> ser.searchsorted(["bread"], side="right") 

3572 array([3]) 

3573 

3574 If the values are not monotonically sorted, wrong locations 

3575 may be returned: 

3576 

3577 >>> ser = pd.Series([2, 1, 3]) 

3578 >>> ser 

3579 0 2 

3580 1 1 

3581 2 3 

3582 dtype: int64 

3583 >>> ser.searchsorted(1) # doctest: +SKIP 

3584 0 # wrong result, correct would be 1 

3585 """ 

3586 return base.IndexOpsMixin.searchsorted(self, value, side=side, sorter=sorter) 

3587 

3588 # ------------------------------------------------------------------- 

3589 # Combination 

3590 

3591 def _append_internal(self, to_append: Series, ignore_index: bool = False) -> Series: 

3592 from pandas.core.reshape.concat import concat 

3593 

3594 return concat([self, to_append], ignore_index=ignore_index) 

3595 

3596 def compare( 

3597 self, 

3598 other: Series, 

3599 align_axis: Axis = 1, 

3600 keep_shape: bool = False, 

3601 keep_equal: bool = False, 

3602 result_names: Suffixes = ("self", "other"), 

3603 ) -> DataFrame | Series: 

3604 """ 

3605 Compare to another Series and show the differences. 

3606 

3607 This method aligns two Series and highlights only the values that 

3608 differ between them. Equal values are shown as NaN by default. 

3609 

3610 Parameters 

3611 ---------- 

3612 other : Series 

3613 Object to compare with. 

3614 

3615 align_axis : {0 or 'index', 1 or 'columns'}, default 1 

3616 Determine which axis to align the comparison on. 

3617 

3618 * 0, or 'index' : Resulting differences are stacked vertically 

3619 with rows drawn alternately from self and other. 

3620 * 1, or 'columns' : Resulting differences are aligned horizontally 

3621 with columns drawn alternately from self and other. 

3622 

3623 keep_shape : bool, default False 

3624 If true, all rows and columns are kept. 

3625 Otherwise, only the ones with different values are kept. 

3626 

3627 keep_equal : bool, default False 

3628 If true, the result keeps values that are equal. 

3629 Otherwise, equal values are shown as NaNs. 

3630 

3631 result_names : tuple, default ('self', 'other') 

3632 Set the dataframes names in the comparison. 

3633 

3634 Returns 

3635 ------- 

3636 Series or DataFrame 

3637 If axis is 0 or 'index' the result will be a Series. 

3638 The resulting index will be a MultiIndex with 'self' and 'other' 

3639 stacked alternately at the inner level. 

3640 

3641 If axis is 1 or 'columns' the result will be a DataFrame. 

3642 It will have two columns namely 'self' and 'other'. 

3643 

3644 See Also 

3645 -------- 

3646 DataFrame.compare : Compare with another DataFrame and show differences. 

3647 

3648 Notes 

3649 ----- 

3650 Matching NaNs will not appear as a difference. 

3651 

3652 Examples 

3653 -------- 

3654 >>> s1 = pd.Series(["a", "b", "c", "d", "e"]) 

3655 >>> s2 = pd.Series(["a", "a", "c", "b", "e"]) 

3656 

3657 Align the differences on columns 

3658 

3659 >>> s1.compare(s2) 

3660 self other 

3661 1 b a 

3662 3 d b 

3663 

3664 Stack the differences on indices 

3665 

3666 >>> s1.compare(s2, align_axis=0) 

3667 1 self b 

3668 other a 

3669 3 self d 

3670 other b 

3671 dtype: str 

3672 

3673 Keep all original rows 

3674 

3675 >>> s1.compare(s2, keep_shape=True) 

3676 self other 

3677 0 NaN NaN 

3678 1 b a 

3679 2 NaN NaN 

3680 3 d b 

3681 4 NaN NaN 

3682 

3683 Keep all original rows and also all original values 

3684 

3685 >>> s1.compare(s2, keep_shape=True, keep_equal=True) 

3686 self other 

3687 0 a a 

3688 1 b a 

3689 2 c c 

3690 3 d b 

3691 4 e e 

3692 """ 

3693 

3694 return super().compare( 

3695 other=other, 

3696 align_axis=align_axis, 

3697 keep_shape=keep_shape, 

3698 keep_equal=keep_equal, 

3699 result_names=result_names, 

3700 ) 

3701 

3702 def combine( 

3703 self, 

3704 other: Series | Hashable, 

3705 func: Callable[[Hashable, Hashable], Hashable], 

3706 fill_value: Hashable | None = None, 

3707 ) -> Series: 

3708 """ 

3709 Combine the Series with a Series or scalar according to `func`. 

3710 

3711 Combine the Series and `other` using `func` to perform elementwise 

3712 selection for combined Series. 

3713 `fill_value` is assumed when value is not present at some index 

3714 from one of the two Series being combined. The result index is the 

3715 union of the two indexes. If a label is duplicated, its occurrences 

3716 are paired in order: the first occurrence in the Series with the first 

3717 in `other`, the second with the second, and so on; an occurrence with 

3718 no counterpart is paired with `fill_value`. 

3719 

3720 Parameters 

3721 ---------- 

3722 other : Series or scalar 

3723 The value(s) to be combined with the `Series`. 

3724 func : function 

3725 Function that takes two scalars as inputs and returns an element. 

3726 fill_value : scalar, optional 

3727 The value to assume when an index is missing from 

3728 one Series or the other. The default specifies to use the 

3729 appropriate NA value for the underlying dtype of the Series. 

3730 

3731 Returns 

3732 ------- 

3733 Series 

3734 The result of combining the Series with the other object. 

3735 

3736 See Also 

3737 -------- 

3738 Series.combine_first : Combine Series values, choosing the calling 

3739 Series' values first. 

3740 

3741 Examples 

3742 -------- 

3743 Consider 2 Datasets ``s1`` and ``s2`` containing 

3744 highest clocked speeds of different birds. 

3745 

3746 >>> s1 = pd.Series({"falcon": 330.0, "eagle": 160.0}) 

3747 >>> s1 

3748 falcon 330.0 

3749 eagle 160.0 

3750 dtype: float64 

3751 >>> s2 = pd.Series({"falcon": 345.0, "eagle": 200.0, "duck": 30.0}) 

3752 >>> s2 

3753 falcon 345.0 

3754 eagle 200.0 

3755 duck 30.0 

3756 dtype: float64 

3757 

3758 Now, to combine the two datasets and view the highest speeds 

3759 of the birds across the two datasets 

3760 

3761 >>> s1.combine(s2, max) 

3762 duck NaN 

3763 eagle 200.0 

3764 falcon 345.0 

3765 dtype: float64 

3766 

3767 In the previous example, the resulting value for duck is missing, 

3768 because the maximum of a NaN and a float is a NaN. 

3769 So, in the example, we set ``fill_value=0``, 

3770 so the maximum value returned will be the value from some dataset. 

3771 

3772 >>> s1.combine(s2, max, fill_value=0) 

3773 duck 30.0 

3774 eagle 200.0 

3775 falcon 345.0 

3776 dtype: float64 

3777 

3778 Occurrences of a duplicated label are paired in order. Below, the 

3779 first ``"a"`` in ``s3`` is combined with the ``"a"`` in ``s4``, 

3780 while the second has no counterpart and is paired with 

3781 ``fill_value``. 

3782 

3783 >>> s3 = pd.Series([1, 2, 3], index=["a", "a", "b"]) 

3784 >>> s4 = pd.Series([10, 20], index=["a", "b"]) 

3785 >>> s3.combine(s4, lambda x, y: x + y, fill_value=0) 

3786 a 11 

3787 a 2 

3788 b 23 

3789 dtype: int64 

3790 """ 

3791 if fill_value is None: 

3792 fill_value = na_value_for_dtype(self.dtype, compat=False) 

3793 

3794 if isinstance(other, Series): 

3795 if ( 

3796 isinstance(self.index, MultiIndex) 

3797 and isinstance(other.index, MultiIndex) 

3798 and self.index.nlevels != other.index.nlevels 

3799 ): 

3800 raise ValueError( 

3801 "Cannot combine Series whose MultiIndexes have different " 

3802 f"numbers of levels: {self.index.nlevels} and " 

3803 f"{other.index.nlevels}" 

3804 ) 

3805 new_index = self.index.union(other.index) 

3806 if self.index.equals(new_index) and other.index.equals(new_index): 

3807 lindexer = rindexer = range(len(new_index)) 

3808 elif self.index._index_as_unique and other.index._index_as_unique: 

3809 lindexer = self.index.get_indexer(new_index).tolist() 

3810 rindexer = other.index.get_indexer(new_index).tolist() 

3811 else: 

3812 lindexer = self.index._pairwise_indexer(new_index).tolist() 

3813 rindexer = other.index._pairwise_indexer(new_index).tolist() 

3814 new_name = ops.get_op_result_name(self, other) 

3815 new_values = np.empty(len(new_index), dtype=object) 

3816 lvalues = self._values 

3817 rvalues = other._values 

3818 with np.errstate(all="ignore"): 

3819 for i, (li, ri) in enumerate(zip(lindexer, rindexer, strict=True)): 

3820 lv = lvalues[li] if li != -1 else fill_value 

3821 rv = rvalues[ri] if ri != -1 else fill_value 

3822 new_values[i] = func(lv, rv) 

3823 else: 

3824 # Assume that other is a scalar, so apply the function for 

3825 # each element in the Series 

3826 new_index = self.index 

3827 new_values = np.empty(len(new_index), dtype=object) 

3828 with np.errstate(all="ignore"): 

3829 new_values[:] = [func(lv, other) for lv in self._values] 

3830 new_name = self.name 

3831 

3832 res_values = self.array._cast_pointwise_result(new_values) 

3833 return self._constructor( 

3834 res_values, 

3835 dtype=res_values.dtype, 

3836 index=new_index, 

3837 name=new_name, 

3838 copy=False, 

3839 ) 

3840 

3841 def combine_first(self, other) -> Series: 

3842 """ 

3843 Update null elements with value in the same location in 'other'. 

3844 

3845 Combine two Series objects by filling null values in one Series with 

3846 non-null values from the other Series. Result index will be the union 

3847 of the two indexes. 

3848 

3849 Parameters 

3850 ---------- 

3851 other : Series 

3852 The value(s) to be used for filling null values. 

3853 

3854 Returns 

3855 ------- 

3856 Series 

3857 The result of combining the provided Series with the other object. 

3858 

3859 See Also 

3860 -------- 

3861 Series.combine : Perform element-wise operation on two Series 

3862 using a given function. 

3863 

3864 Examples 

3865 -------- 

3866 >>> s1 = pd.Series([1, np.nan]) 

3867 >>> s2 = pd.Series([3, 4, 5]) 

3868 >>> s1.combine_first(s2) 

3869 0 1.0 

3870 1 4.0 

3871 2 5.0 

3872 dtype: float64 

3873 

3874 Null values still persist if the location of that null value 

3875 does not exist in `other` 

3876 

3877 >>> s1 = pd.Series({"falcon": np.nan, "eagle": 160.0}) 

3878 >>> s2 = pd.Series({"eagle": 200.0, "duck": 30.0}) 

3879 >>> s1.combine_first(s2) 

3880 duck 30.0 

3881 eagle 160.0 

3882 falcon NaN 

3883 dtype: float64 

3884 """ 

3885 from pandas.core.reshape.concat import concat 

3886 

3887 if self.dtype == other.dtype: 

3888 if self.index.equals(other.index): 

3889 return self.mask(self.isna(), other) 

3890 

3891 new_index = self.index.union(other.index) 

3892 

3893 this = self 

3894 # identify the index subset to keep for each series 

3895 keep_other = other.index.difference(this.index[notna(this)]) 

3896 keep_this = this.index.difference(keep_other) 

3897 

3898 this = this.reindex(keep_this) 

3899 other = other.reindex(keep_other) 

3900 

3901 if this.dtype.kind == "M" and other.dtype.kind != "M": 

3902 # TODO: try to match resos? 

3903 other = to_datetime(other) 

3904 warnings.warn( 

3905 # GH#62931 

3906 "Silently casting non-datetime 'other' to datetime in " 

3907 "Series.combine_first is deprecated and will be removed " 

3908 "in a future version. Explicitly cast before calling " 

3909 "combine_first instead.", 

3910 Pandas4Warning, 

3911 stacklevel=find_stack_level(), 

3912 ) 

3913 

3914 combined = concat([this, other]) 

3915 combined = combined.reindex(new_index) 

3916 return combined.__finalize__(self, method="combine_first") 

3917 

3918 def update(self, other: Series | Sequence | Mapping) -> None: 

3919 """ 

3920 Modify Series in place using values from passed Series. 

3921 

3922 Uses non-NA values from passed Series to make updates. Aligns 

3923 on index. 

3924 

3925 Parameters 

3926 ---------- 

3927 other : Series, or object coercible into Series 

3928 Other Series that provides values to update the current Series. 

3929 

3930 See Also 

3931 -------- 

3932 Series.combine : Perform element-wise operation on two Series 

3933 using a given function. 

3934 Series.transform: Modify a Series using a function. 

3935 

3936 Examples 

3937 -------- 

3938 >>> s = pd.Series([1, 2, 3]) 

3939 >>> s.update(pd.Series([4, 5, 6])) 

3940 >>> s 

3941 0 4 

3942 1 5 

3943 2 6 

3944 dtype: int64 

3945 

3946 >>> s = pd.Series(["a", "b", "c"]) 

3947 >>> s.update(pd.Series(["d", "e"], index=[0, 2])) 

3948 >>> s 

3949 0 d 

3950 1 b 

3951 2 e 

3952 dtype: str 

3953 

3954 >>> s = pd.Series([1, 2, 3]) 

3955 >>> s.update(pd.Series([4, 5, 6, 7, 8])) 

3956 >>> s 

3957 0 4 

3958 1 5 

3959 2 6 

3960 dtype: int64 

3961 

3962 If ``other`` contains NaNs the corresponding values are not updated 

3963 in the original Series. 

3964 

3965 >>> s = pd.Series([1, 2, 3]) 

3966 >>> s.update(pd.Series([4, np.nan, 6])) 

3967 >>> s 

3968 0 4 

3969 1 2 

3970 2 6 

3971 dtype: int64 

3972 

3973 ``other`` can also be a non-Series object type 

3974 that is coercible into a Series 

3975 

3976 >>> s = pd.Series([1, 2, 3]) 

3977 >>> s.update([4, np.nan, 6]) 

3978 >>> s 

3979 0 4 

3980 1 2 

3981 2 6 

3982 dtype: int64 

3983 

3984 >>> s = pd.Series([1, 2, 3]) 

3985 >>> s.update({1: 9}) 

3986 >>> s 

3987 0 1 

3988 1 9 

3989 2 3 

3990 dtype: int64 

3991 """ 

3992 if not CHAINED_WARNING_DISABLED: 

3993 if sys.getrefcount( 

3994 self 

3995 ) <= REF_COUNT_METHOD and not com.is_local_in_caller_frame(self): 

3996 warnings.warn( 

3997 _chained_assignment_method_update_msg, 

3998 ChainedAssignmentError, 

3999 stacklevel=2, 

4000 ) 

4001 

4002 if not isinstance(other, Series): 

4003 other = Series(other) 

4004 

4005 other = other.reindex_like(self) 

4006 mask = notna(other) 

4007 

4008 self._mgr = self._mgr.putmask(mask=mask, new=other) 

4009 

4010 # ---------------------------------------------------------------------- 

4011 # Reindexing, sorting 

4012 

4013 @overload 

4014 def sort_values( 

4015 self, 

4016 *, 

4017 axis: Axis = ..., 

4018 ascending: bool | Sequence[bool] = ..., 

4019 inplace: Literal[False] = ..., 

4020 kind: SortKind = ..., 

4021 na_position: NaPosition = ..., 

4022 ignore_index: bool = ..., 

4023 key: ValueKeyFunc = ..., 

4024 ) -> Series: ... 

4025 

4026 @overload 

4027 def sort_values( 

4028 self, 

4029 *, 

4030 axis: Axis = ..., 

4031 ascending: bool | Sequence[bool] = ..., 

4032 inplace: Literal[True], 

4033 kind: SortKind = ..., 

4034 na_position: NaPosition = ..., 

4035 ignore_index: bool = ..., 

4036 key: ValueKeyFunc = ..., 

4037 ) -> None: ... 

4038 

4039 @overload 

4040 def sort_values( 

4041 self, 

4042 *, 

4043 axis: Axis = ..., 

4044 ascending: bool | Sequence[bool] = ..., 

4045 inplace: bool | lib.NoDefault = ..., 

4046 kind: SortKind = ..., 

4047 na_position: NaPosition = ..., 

4048 ignore_index: bool = ..., 

4049 key: ValueKeyFunc = ..., 

4050 ) -> Series | None: ... 

4051 

4052 def sort_values( 

4053 self, 

4054 *, 

4055 axis: Axis = 0, 

4056 ascending: bool | Sequence[bool] = True, 

4057 inplace: bool | lib.NoDefault = lib.no_default, 

4058 kind: SortKind = "quicksort", 

4059 na_position: NaPosition = "last", 

4060 ignore_index: bool = False, 

4061 key: ValueKeyFunc | None = None, 

4062 ) -> Series | None: 

4063 """ 

4064 Sort by the values. 

4065 

4066 Sort a Series in ascending or descending order by some 

4067 criterion. 

4068 

4069 Parameters 

4070 ---------- 

4071 axis : {0 or 'index'} 

4072 Unused. Parameter needed for compatibility with DataFrame. 

4073 ascending : bool or list of bools, default True 

4074 If True, sort values in ascending order, otherwise descending. 

4075 inplace : bool, default False 

4076 If True, perform operation in-place. 

4077 

4078 .. deprecated:: 3.1.0 

4079 

4080 This keyword is deprecated and will be removed in pandas 4.0. 

4081 See the `whatsnew note on PDEP-8 

4082 <https://pandas.pydata.org/docs/dev/whatsnew/v3.1.0.html#deprecation-inplace>`__ 

4083 for more details. 

4084 

4085 kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, default 'quicksort' 

4086 Choice of sorting algorithm. See also :func:`numpy.sort` for more 

4087 information. The sort order is deterministic for a given input. 

4088 `mergesort` and `stable` are the only stable algorithms, which preserve 

4089 the relative order of equal keys. 

4090 na_position : {'first' or 'last'}, default 'last' 

4091 Argument 'first' puts NaNs at the beginning, 'last' puts NaNs at 

4092 the end. 

4093 ignore_index : bool, default False 

4094 If True, the resulting axis will be labeled 0, 1, …, n - 1. 

4095 key : callable, optional 

4096 If not None, apply the key function to the series values 

4097 before sorting. This is similar to the `key` argument in the 

4098 builtin :meth:`sorted` function, with the notable difference that 

4099 this `key` function should be *vectorized*. It should expect a 

4100 ``Series`` and return an array-like. 

4101 

4102 Returns 

4103 ------- 

4104 Series or None 

4105 Series ordered by values or None if ``inplace=True``. 

4106 

4107 See Also 

4108 -------- 

4109 Series.sort_index : Sort by the Series indices. 

4110 DataFrame.sort_values : Sort DataFrame by the values along either axis. 

4111 DataFrame.sort_index : Sort DataFrame by indices. 

4112 

4113 Examples 

4114 -------- 

4115 >>> s = pd.Series([np.nan, 1, 3, 10, 5]) 

4116 >>> s 

4117 0 NaN 

4118 1 1.0 

4119 2 3.0 

4120 3 10.0 

4121 4 5.0 

4122 dtype: float64 

4123 

4124 Sort values ascending order (default behavior) 

4125 

4126 >>> s.sort_values(ascending=True) 

4127 1 1.0 

4128 2 3.0 

4129 4 5.0 

4130 3 10.0 

4131 0 NaN 

4132 dtype: float64 

4133 

4134 Sort values descending order 

4135 

4136 >>> s.sort_values(ascending=False) 

4137 3 10.0 

4138 4 5.0 

4139 2 3.0 

4140 1 1.0 

4141 0 NaN 

4142 dtype: float64 

4143 

4144 Sort values putting NAs first 

4145 

4146 >>> s.sort_values(na_position="first") 

4147 0 NaN 

4148 1 1.0 

4149 2 3.0 

4150 4 5.0 

4151 3 10.0 

4152 dtype: float64 

4153 

4154 Sort a series of strings 

4155 

4156 >>> s = pd.Series(["z", "b", "d", "a", "c"]) 

4157 >>> s 

4158 0 z 

4159 1 b 

4160 2 d 

4161 3 a 

4162 4 c 

4163 dtype: str 

4164 

4165 >>> s.sort_values() 

4166 3 a 

4167 1 b 

4168 4 c 

4169 2 d 

4170 0 z 

4171 dtype: str 

4172 

4173 Sort using a key function. Your `key` function will be 

4174 given the ``Series`` of values and should return an array-like. 

4175 

4176 >>> s = pd.Series(["a", "B", "c", "D", "e"]) 

4177 >>> s.sort_values() 

4178 1 B 

4179 3 D 

4180 0 a 

4181 2 c 

4182 4 e 

4183 dtype: str 

4184 >>> s.sort_values(key=lambda x: x.str.lower()) 

4185 0 a 

4186 1 B 

4187 2 c 

4188 3 D 

4189 4 e 

4190 dtype: str 

4191 

4192 NumPy ufuncs work well here. For example, we can 

4193 sort by the ``sin`` of the value 

4194 

4195 >>> s = pd.Series([-4, -2, 0, 2, 4]) 

4196 >>> s.sort_values(key=np.sin) 

4197 1 -2 

4198 4 4 

4199 2 0 

4200 0 -4 

4201 3 2 

4202 dtype: int64 

4203 

4204 More complicated user-defined functions can be used, 

4205 as long as they expect a Series and return an array-like 

4206 

4207 >>> s.sort_values(key=lambda x: np.tan(x.cumsum())) 

4208 0 -4 

4209 3 2 

4210 4 4 

4211 1 -2 

4212 2 0 

4213 dtype: int64 

4214 """ 

4215 inplace = self._check_inplace_deprecation(inplace, "sort_values") 

4216 inplace = validate_bool_kwarg(inplace, "inplace") 

4217 # Validate the axis parameter 

4218 self._get_axis_number(axis) 

4219 

4220 if is_list_like(ascending): 

4221 ascending = cast("Sequence[bool]", ascending) 

4222 if len(ascending) != 1: 

4223 raise ValueError( 

4224 f"Length of ascending ({len(ascending)}) must be 1 for Series" 

4225 ) 

4226 ascending = ascending[0] 

4227 

4228 ascending = validate_ascending(ascending) 

4229 

4230 if na_position not in ["first", "last"]: 

4231 raise ValueError(f"invalid na_position: {na_position}") 

4232 

4233 # GH 35922. Make sorting stable by leveraging nargsort 

4234 if key: 

4235 values_to_sort = cast("Series", ensure_key_mapped(self, key))._values 

4236 else: 

4237 values_to_sort = self._values 

4238 sorted_index = nargsort(values_to_sort, kind, bool(ascending), na_position) 

4239 

4240 if is_range_indexer(sorted_index, len(sorted_index)): 

4241 result = self if inplace else self.copy(deep=False) 

4242 if ignore_index: 

4243 result.index = default_index(len(sorted_index)) 

4244 if inplace: 

4245 return None 

4246 return result 

4247 

4248 result = self._constructor( 

4249 self._values[sorted_index], index=self.index[sorted_index], copy=False 

4250 ) 

4251 

4252 if ignore_index: 

4253 result.index = default_index(len(sorted_index)) 

4254 

4255 if not inplace: 

4256 return result.__finalize__(self, method="sort_values") 

4257 self._update_inplace(result) 

4258 return None 

4259 

4260 @overload 

4261 def sort_index( 

4262 self, 

4263 *, 

4264 axis: Axis = ..., 

4265 level: IndexLabel = ..., 

4266 ascending: bool | Sequence[bool] = ..., 

4267 inplace: Literal[True], 

4268 kind: SortKind = ..., 

4269 na_position: NaPosition = ..., 

4270 sort_remaining: bool = ..., 

4271 ignore_index: bool = ..., 

4272 key: IndexKeyFunc = ..., 

4273 ) -> None: ... 

4274 

4275 @overload 

4276 def sort_index( 

4277 self, 

4278 *, 

4279 axis: Axis = ..., 

4280 level: IndexLabel = ..., 

4281 ascending: bool | Sequence[bool] = ..., 

4282 inplace: Literal[False] = ..., 

4283 kind: SortKind = ..., 

4284 na_position: NaPosition = ..., 

4285 sort_remaining: bool = ..., 

4286 ignore_index: bool = ..., 

4287 key: IndexKeyFunc = ..., 

4288 ) -> Series: ... 

4289 

4290 @overload 

4291 def sort_index( 

4292 self, 

4293 *, 

4294 axis: Axis = ..., 

4295 level: IndexLabel = ..., 

4296 ascending: bool | Sequence[bool] = ..., 

4297 inplace: bool | lib.NoDefault = ..., 

4298 kind: SortKind = ..., 

4299 na_position: NaPosition = ..., 

4300 sort_remaining: bool = ..., 

4301 ignore_index: bool = ..., 

4302 key: IndexKeyFunc = ..., 

4303 ) -> Series | None: ... 

4304 

4305 def sort_index( 

4306 self, 

4307 *, 

4308 axis: Axis = 0, 

4309 level: IndexLabel | None = None, 

4310 ascending: bool | Sequence[bool] = True, 

4311 inplace: bool | lib.NoDefault = lib.no_default, 

4312 kind: SortKind = "quicksort", 

4313 na_position: NaPosition = "last", 

4314 sort_remaining: bool = True, 

4315 ignore_index: bool = False, 

4316 key: IndexKeyFunc | None = None, 

4317 ) -> Series | None: 

4318 """ 

4319 Sort Series by index labels. 

4320 

4321 Returns a new Series sorted by label if `inplace` argument is 

4322 ``False``, otherwise updates the original series and returns None. 

4323 

4324 Parameters 

4325 ---------- 

4326 axis : {0 or 'index'} 

4327 Unused. Parameter needed for compatibility with DataFrame. 

4328 level : int, optional 

4329 If not None, sort on values in specified index level(s). 

4330 ascending : bool or list-like of bools, default True 

4331 Sort ascending vs. descending. When the index is a MultiIndex the 

4332 sort direction can be controlled for each level individually. 

4333 inplace : bool, default False 

4334 If True, perform operation in-place. 

4335 

4336 .. deprecated:: 3.1.0 

4337 

4338 This keyword is deprecated and will be removed in pandas 4.0. 

4339 See the `whatsnew note on PDEP-8 

4340 <https://pandas.pydata.org/docs/dev/whatsnew/v3.1.0.html#deprecation-inplace>`__ 

4341 for more details. 

4342 

4343 kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, default 'quicksort' 

4344 Choice of sorting algorithm. See also :func:`numpy.sort` for more 

4345 information. The sort order is deterministic for a given input. 

4346 'mergesort' and 'stable' are the only stable algorithms, which preserve 

4347 the relative order of equal keys. This option is ignored when sorting on a 

4348 MultiIndex or when a `level` is specified. 

4349 na_position : {'first', 'last'}, default 'last' 

4350 If 'first' puts NaNs at the beginning, 'last' puts NaNs at the end. 

4351 Not implemented for MultiIndex. 

4352 sort_remaining : bool, default True 

4353 If True and sorting by level and index is multilevel, sort by other 

4354 levels too (in order) after sorting by specified level. 

4355 ignore_index : bool, default False 

4356 If True, the resulting axis will be labeled 0, 1, …, n - 1. 

4357 key : callable, optional 

4358 If not None, apply the key function to the index values 

4359 before sorting. This is similar to the `key` argument in the 

4360 builtin :meth:`sorted` function, with the notable difference that 

4361 this `key` function should be *vectorized*. It should expect an 

4362 ``Index`` and return an ``Index`` of the same shape. 

4363 

4364 Returns 

4365 ------- 

4366 Series or None 

4367 The original Series sorted by the labels or None if ``inplace=True``. 

4368 

4369 See Also 

4370 -------- 

4371 DataFrame.sort_index: Sort DataFrame by the index. 

4372 DataFrame.sort_values: Sort DataFrame by the value. 

4373 Series.sort_values : Sort Series by the value. 

4374 

4375 Examples 

4376 -------- 

4377 >>> s = pd.Series(["a", "b", "c", "d"], index=[3, 2, 1, 4]) 

4378 >>> s.sort_index() 

4379 1 c 

4380 2 b 

4381 3 a 

4382 4 d 

4383 dtype: str 

4384 

4385 Sort Descending 

4386 

4387 >>> s.sort_index(ascending=False) 

4388 4 d 

4389 3 a 

4390 2 b 

4391 1 c 

4392 dtype: str 

4393 

4394 By default NaNs are put at the end, but use `na_position` to place 

4395 them at the beginning 

4396 

4397 >>> s = pd.Series(["a", "b", "c", "d"], index=[3, 2, 1, np.nan]) 

4398 >>> s.sort_index(na_position="first") 

4399 NaN d 

4400 1.0 c 

4401 2.0 b 

4402 3.0 a 

4403 dtype: str 

4404 

4405 Specify index level to sort 

4406 

4407 >>> arrays = [ 

4408 ... np.array(["qux", "qux", "foo", "foo", "baz", "baz", "bar", "bar"]), 

4409 ... np.array(["two", "one", "two", "one", "two", "one", "two", "one"]), 

4410 ... ] 

4411 >>> s = pd.Series([1, 2, 3, 4, 5, 6, 7, 8], index=arrays) 

4412 >>> s.sort_index(level=1) 

4413 bar one 8 

4414 baz one 6 

4415 foo one 4 

4416 qux one 2 

4417 bar two 7 

4418 baz two 5 

4419 foo two 3 

4420 qux two 1 

4421 dtype: int64 

4422 

4423 Does not sort by remaining levels when sorting by levels 

4424 

4425 >>> s.sort_index(level=1, sort_remaining=False) 

4426 qux one 2 

4427 foo one 4 

4428 baz one 6 

4429 bar one 8 

4430 qux two 1 

4431 foo two 3 

4432 baz two 5 

4433 bar two 7 

4434 dtype: int64 

4435 

4436 Apply a key function before sorting 

4437 

4438 >>> s = pd.Series([1, 2, 3, 4], index=["A", "b", "C", "d"]) 

4439 >>> s.sort_index(key=lambda x: x.str.lower()) 

4440 A 1 

4441 b 2 

4442 C 3 

4443 d 4 

4444 dtype: int64 

4445 """ 

4446 inplace = self._check_inplace_deprecation(inplace, "sort_index") 

4447 

4448 return super().sort_index( 

4449 axis=axis, 

4450 level=level, 

4451 ascending=ascending, 

4452 inplace=inplace, 

4453 kind=kind, 

4454 na_position=na_position, 

4455 sort_remaining=sort_remaining, 

4456 ignore_index=ignore_index, 

4457 key=key, 

4458 ) 

4459 

4460 def argsort( 

4461 self, 

4462 axis: Axis = 0, 

4463 kind: SortKind = "quicksort", 

4464 order: None = None, 

4465 stable: None = None, 

4466 ) -> Series: 

4467 """ 

4468 Return the integer indices that would sort the Series values. 

4469 

4470 Override ndarray.argsort. Argsorts the value, omitting NA/null values, 

4471 and places the result in the same locations as the non-NA values. 

4472 

4473 Parameters 

4474 ---------- 

4475 axis : {0 or 'index'} 

4476 Unused. Parameter needed for compatibility with DataFrame. 

4477 kind : {'mergesort', 'quicksort', 'heapsort', 'stable'}, default 'quicksort' 

4478 Choice of sorting algorithm. See :func:`numpy.sort` for more 

4479 information. 'mergesort' and 'stable' are the only stable algorithms. 

4480 order : None 

4481 Has no effect but is accepted for compatibility with numpy. 

4482 stable : None 

4483 Has no effect but is accepted for compatibility with numpy. 

4484 

4485 Returns 

4486 ------- 

4487 Series[np.intp] 

4488 Positions of values within the sort order with -1 indicating 

4489 nan values. 

4490 

4491 See Also 

4492 -------- 

4493 numpy.ndarray.argsort : Returns the indices that would sort this array. 

4494 

4495 Examples 

4496 -------- 

4497 >>> s = pd.Series([3, 2, 1]) 

4498 >>> s.argsort() 

4499 0 2 

4500 1 1 

4501 2 0 

4502 dtype: int64 

4503 """ 

4504 if axis != -1: 

4505 # GH#54257 We allow -1 here so that np.argsort(series) works 

4506 self._get_axis_number(axis) 

4507 

4508 result = self.array.argsort(kind=kind) 

4509 

4510 res = self._constructor( 

4511 result, index=self.index, name=self.name, dtype=np.intp, copy=False 

4512 ) 

4513 return res.__finalize__(self, method="argsort") 

4514 

4515 def nlargest( 

4516 self, n: int = 5, keep: Literal["first", "last", "all"] = "first" 

4517 ) -> Series: 

4518 """ 

4519 Return the largest `n` elements. 

4520 

4521 This method is optimized for performance compared to sorting the 

4522 entire Series when only a few of the top values are needed. 

4523 

4524 Parameters 

4525 ---------- 

4526 n : int, default 5 

4527 Return this many descending sorted values. 

4528 keep : {'first', 'last', 'all'}, default 'first' 

4529 When there are duplicate values that cannot all fit in a 

4530 Series of `n` elements: 

4531 

4532 - ``first`` : return the first `n` occurrences in order 

4533 of appearance. 

4534 - ``last`` : return the last `n` occurrences in reverse 

4535 order of appearance. 

4536 - ``all`` : keep all occurrences. This can result in a Series of 

4537 size larger than `n`. 

4538 

4539 Returns 

4540 ------- 

4541 Series 

4542 The `n` largest values in the Series, sorted in decreasing order. 

4543 

4544 See Also 

4545 -------- 

4546 Series.nsmallest: Get the `n` smallest elements. 

4547 Series.sort_values: Sort Series by values. 

4548 Series.head: Return the first `n` rows. 

4549 

4550 Notes 

4551 ----- 

4552 Faster than ``.sort_values(ascending=False).head(n)`` for small `n` 

4553 relative to the size of the ``Series`` object. 

4554 

4555 Examples 

4556 -------- 

4557 >>> countries_population = { 

4558 ... "Italy": 59000000, 

4559 ... "France": 65000000, 

4560 ... "Malta": 434000, 

4561 ... "Maldives": 434000, 

4562 ... "Brunei": 434000, 

4563 ... "Iceland": 337000, 

4564 ... "Nauru": 11300, 

4565 ... "Tuvalu": 11300, 

4566 ... "Anguilla": 11300, 

4567 ... "Montserrat": 5200, 

4568 ... } 

4569 >>> s = pd.Series(countries_population) 

4570 >>> s 

4571 Italy 59000000 

4572 France 65000000 

4573 Malta 434000 

4574 Maldives 434000 

4575 Brunei 434000 

4576 Iceland 337000 

4577 Nauru 11300 

4578 Tuvalu 11300 

4579 Anguilla 11300 

4580 Montserrat 5200 

4581 dtype: int64 

4582 

4583 The `n` largest elements where ``n=5`` by default. 

4584 

4585 >>> s.nlargest() 

4586 France 65000000 

4587 Italy 59000000 

4588 Malta 434000 

4589 Maldives 434000 

4590 Brunei 434000 

4591 dtype: int64 

4592 

4593 The `n` largest elements where ``n=3``. Default `keep` value is 'first' 

4594 so Malta will be kept. 

4595 

4596 >>> s.nlargest(3) 

4597 France 65000000 

4598 Italy 59000000 

4599 Malta 434000 

4600 dtype: int64 

4601 

4602 The `n` largest elements where ``n=3`` and keeping the last duplicates. 

4603 Brunei will be kept since it is the last with value 434000 based on 

4604 the index order. 

4605 

4606 >>> s.nlargest(3, keep="last") 

4607 France 65000000 

4608 Italy 59000000 

4609 Brunei 434000 

4610 dtype: int64 

4611 

4612 The `n` largest elements where ``n=3`` with all duplicates kept. Note 

4613 that the returned Series has five elements due to the three duplicates. 

4614 

4615 >>> s.nlargest(3, keep="all") 

4616 France 65000000 

4617 Italy 59000000 

4618 Malta 434000 

4619 Maldives 434000 

4620 Brunei 434000 

4621 dtype: int64 

4622 """ 

4623 return selectn.SelectNSeries(self, n=n, keep=keep).nlargest() 

4624 

4625 def nsmallest( 

4626 self, n: int = 5, keep: Literal["first", "last", "all"] = "first" 

4627 ) -> Series: 

4628 """ 

4629 Return the smallest `n` elements. 

4630 

4631 This method is optimized for performance compared to sorting the 

4632 entire Series when only a few of the bottom values are needed. 

4633 

4634 Parameters 

4635 ---------- 

4636 n : int, default 5 

4637 Return this many ascending sorted values. 

4638 keep : {'first', 'last', 'all'}, default 'first' 

4639 When there are duplicate values that cannot all fit in a 

4640 Series of `n` elements: 

4641 

4642 - ``first`` : return the first `n` occurrences in order 

4643 of appearance. 

4644 - ``last`` : return the last `n` occurrences in reverse 

4645 order of appearance. 

4646 - ``all`` : keep all occurrences. This can result in a Series of 

4647 size larger than `n`. 

4648 

4649 Returns 

4650 ------- 

4651 Series 

4652 The `n` smallest values in the Series, sorted in increasing order. 

4653 

4654 See Also 

4655 -------- 

4656 Series.nlargest: Get the `n` largest elements. 

4657 Series.sort_values: Sort Series by values. 

4658 Series.head: Return the first `n` rows. 

4659 

4660 Notes 

4661 ----- 

4662 Faster than ``.sort_values().head(n)`` for small `n` relative to 

4663 the size of the ``Series`` object. 

4664 

4665 Examples 

4666 -------- 

4667 >>> countries_population = { 

4668 ... "Italy": 59000000, 

4669 ... "France": 65000000, 

4670 ... "Brunei": 434000, 

4671 ... "Malta": 434000, 

4672 ... "Maldives": 434000, 

4673 ... "Iceland": 337000, 

4674 ... "Nauru": 11300, 

4675 ... "Tuvalu": 11300, 

4676 ... "Anguilla": 11300, 

4677 ... "Montserrat": 5200, 

4678 ... } 

4679 >>> s = pd.Series(countries_population) 

4680 >>> s 

4681 Italy 59000000 

4682 France 65000000 

4683 Brunei 434000 

4684 Malta 434000 

4685 Maldives 434000 

4686 Iceland 337000 

4687 Nauru 11300 

4688 Tuvalu 11300 

4689 Anguilla 11300 

4690 Montserrat 5200 

4691 dtype: int64 

4692 

4693 The `n` smallest elements where ``n=5`` by default. 

4694 

4695 >>> s.nsmallest() 

4696 Montserrat 5200 

4697 Nauru 11300 

4698 Tuvalu 11300 

4699 Anguilla 11300 

4700 Iceland 337000 

4701 dtype: int64 

4702 

4703 The `n` smallest elements where ``n=3``. Default `keep` value is 

4704 'first' so Nauru and Tuvalu will be kept. 

4705 

4706 >>> s.nsmallest(3) 

4707 Montserrat 5200 

4708 Nauru 11300 

4709 Tuvalu 11300 

4710 dtype: int64 

4711 

4712 The `n` smallest elements where ``n=3`` and keeping the last 

4713 duplicates. Anguilla and Tuvalu will be kept since they are the last 

4714 with value 11300 based on the index order. 

4715 

4716 >>> s.nsmallest(3, keep="last") 

4717 Montserrat 5200 

4718 Anguilla 11300 

4719 Tuvalu 11300 

4720 dtype: int64 

4721 

4722 The `n` smallest elements where ``n=3`` with all duplicates kept. Note 

4723 that the returned Series has four elements due to the three duplicates. 

4724 

4725 >>> s.nsmallest(3, keep="all") 

4726 Montserrat 5200 

4727 Nauru 11300 

4728 Tuvalu 11300 

4729 Anguilla 11300 

4730 dtype: int64 

4731 """ 

4732 return selectn.SelectNSeries(self, n=n, keep=keep).nsmallest() 

4733 

4734 def swaplevel( 

4735 self, i: Level = -2, j: Level = -1, copy: bool | lib.NoDefault = lib.no_default 

4736 ) -> Series: 

4737 """ 

4738 Swap levels i and j in a :class:`MultiIndex`. 

4739 

4740 Default is to swap the two innermost levels of the index. 

4741 

4742 Parameters 

4743 ---------- 

4744 i, j : int or str 

4745 Levels of the indices to be swapped. Can pass level name as string. 

4746 copy : bool, default False 

4747 This keyword is now ignored; changing its value will have no 

4748 impact on the method. 

4749 

4750 .. deprecated:: 3.0.0 

4751 

4752 This keyword is ignored and will be removed in pandas 4.0. Since 

4753 pandas 3.0, this method always returns a new object using a lazy 

4754 copy mechanism that defers copies until necessary 

4755 (Copy-on-Write). See the `user guide on Copy-on-Write 

4756 <https://pandas.pydata.org/docs/dev/user_guide/migration.html>`__ 

4757 for more details. 

4758 

4759 Returns 

4760 ------- 

4761 Series 

4762 Series with levels swapped in MultiIndex. 

4763 

4764 See Also 

4765 -------- 

4766 DataFrame.swaplevel : Swap levels i and j in a :class:`DataFrame`. 

4767 Series.reorder_levels : Rearrange index levels using input order. 

4768 MultiIndex.swaplevel : Swap levels i and j in a :class:`MultiIndex`. 

4769 

4770 Examples 

4771 -------- 

4772 >>> s = pd.Series( 

4773 ... ["A", "B", "A", "C"], 

4774 ... index=[ 

4775 ... ["Final exam", "Final exam", "Coursework", "Coursework"], 

4776 ... ["History", "Geography", "History", "Geography"], 

4777 ... ["January", "February", "March", "April"], 

4778 ... ], 

4779 ... ) 

4780 >>> s 

4781 Final exam History January A 

4782 Geography February B 

4783 Coursework History March A 

4784 Geography April C 

4785 dtype: str 

4786 

4787 In the following example, we will swap the levels of the indices. 

4788 Here, we will swap the levels column-wise, but levels can be swapped row-wise 

4789 in a similar manner. Note that column-wise is the default behavior. 

4790 By not supplying any arguments for i and j, we swap the last and second to 

4791 last indices. 

4792 

4793 >>> s.swaplevel() 

4794 Final exam January History A 

4795 February Geography B 

4796 Coursework March History A 

4797 April Geography C 

4798 dtype: str 

4799 

4800 By supplying one argument, we can choose which index to swap the last 

4801 index with. We can for example swap the first index with the last one as 

4802 follows. 

4803 

4804 >>> s.swaplevel(0) 

4805 January History Final exam A 

4806 February Geography Final exam B 

4807 March History Coursework A 

4808 April Geography Coursework C 

4809 dtype: str 

4810 

4811 We can also define explicitly which indices we want to swap by supplying values 

4812 for both i and j. Here, we for example swap the first and second indices. 

4813 

4814 >>> s.swaplevel(0, 1) 

4815 History Final exam January A 

4816 Geography Final exam February B 

4817 History Coursework March A 

4818 Geography Coursework April C 

4819 dtype: str 

4820 """ 

4821 self._check_copy_deprecation(copy) 

4822 assert isinstance(self.index, MultiIndex) 

4823 result = self.copy(deep=False) 

4824 result.index = self.index.swaplevel(i, j) 

4825 return result 

4826 

4827 def reorder_levels(self, order: Sequence[Level]) -> Series: 

4828 """ 

4829 Rearrange index levels using input order. 

4830 

4831 May not drop or duplicate levels. 

4832 

4833 Parameters 

4834 ---------- 

4835 order : list of int representing new level order 

4836 Reference level by number or key. 

4837 

4838 Returns 

4839 ------- 

4840 Series 

4841 Type of caller with index as MultiIndex (new object). 

4842 

4843 See Also 

4844 -------- 

4845 DataFrame.reorder_levels : Rearrange index or column levels using 

4846 input ``order``. 

4847 

4848 Examples 

4849 -------- 

4850 >>> arrays = [ 

4851 ... np.array(["dog", "dog", "cat", "cat", "bird", "bird"]), 

4852 ... np.array(["white", "black", "white", "black", "white", "black"]), 

4853 ... ] 

4854 >>> s = pd.Series([1, 2, 3, 3, 5, 2], index=arrays) 

4855 >>> s 

4856 dog white 1 

4857 black 2 

4858 cat white 3 

4859 black 3 

4860 bird white 5 

4861 black 2 

4862 dtype: int64 

4863 >>> s.reorder_levels([1, 0]) 

4864 white dog 1 

4865 black dog 2 

4866 white cat 3 

4867 black cat 3 

4868 white bird 5 

4869 black bird 2 

4870 dtype: int64 

4871 """ 

4872 if not isinstance(self.index, MultiIndex): # pragma: no cover 

4873 raise Exception("Can only reorder levels on a hierarchical axis.") 

4874 

4875 result = self.copy(deep=False) 

4876 assert isinstance(result.index, MultiIndex) 

4877 result.index = result.index.reorder_levels(order) 

4878 return result 

4879 

4880 def explode(self, ignore_index: bool = False) -> Series: 

4881 """ 

4882 Transform each element of a list-like to a row. 

4883 

4884 This method expands list-like elements so that each item in the list 

4885 gets its own row, while non-list-like elements remain unchanged. 

4886 The index is duplicated for the expanded rows. 

4887 

4888 Parameters 

4889 ---------- 

4890 ignore_index : bool, default False 

4891 If True, the resulting index will be labeled 0, 1, …, n - 1. 

4892 

4893 Returns 

4894 ------- 

4895 Series 

4896 Exploded lists to rows; index will be duplicated for these rows. 

4897 

4898 See Also 

4899 -------- 

4900 Series.str.split : Split string values on specified separator. 

4901 Series.unstack : Unstack, a.k.a. pivot, Series with MultiIndex 

4902 to produce DataFrame. 

4903 DataFrame.melt : Unpivot a DataFrame from wide format to long format. 

4904 DataFrame.explode : Explode a DataFrame from list-like 

4905 columns to long format. 

4906 

4907 Notes 

4908 ----- 

4909 This routine will explode list-likes including lists, tuples, sets, 

4910 Series, and np.ndarray. The result dtype of the subset rows will 

4911 be object. Scalars will be returned unchanged, and empty list-likes will 

4912 result in an np.nan for that row. In addition, the ordering of elements in 

4913 the output will be non-deterministic when exploding sets. 

4914 

4915 Reference :ref:`the user guide <reshaping.explode>` for more examples. 

4916 

4917 Examples 

4918 -------- 

4919 >>> s = pd.Series([[1, 2, 3], "foo", [], [3, 4]]) 

4920 >>> s 

4921 0 [1, 2, 3] 

4922 1 foo 

4923 2 [] 

4924 3 [3, 4] 

4925 dtype: object 

4926 

4927 >>> s.explode() 

4928 0 1 

4929 0 2 

4930 0 3 

4931 1 foo 

4932 2 NaN 

4933 3 3 

4934 3 4 

4935 dtype: object 

4936 """ 

4937 if isinstance(self.dtype, ExtensionDtype): 

4938 values, counts = self._values._explode() 

4939 elif len(self) and is_object_dtype(self.dtype): 

4940 values, counts = reshape.explode(np.asarray(self._values)) 

4941 else: 

4942 result = self.copy() 

4943 return result.reset_index(drop=True) if ignore_index else result 

4944 

4945 if ignore_index: 

4946 index: Index = default_index(len(values)) 

4947 else: 

4948 index = self.index.repeat(counts) 

4949 

4950 return self._constructor(values, index=index, name=self.name, copy=False) 

4951 

4952 def unstack( 

4953 self, 

4954 level: IndexLabel = -1, 

4955 fill_value: Hashable | None = None, 

4956 sort: bool = True, 

4957 ) -> DataFrame: 

4958 """ 

4959 Unstack, also known as pivot, Series with MultiIndex to produce DataFrame. 

4960 

4961 This method pivots a level of the MultiIndex labels, reshaping the 

4962 Series into a DataFrame where the unstacked level becomes the columns. 

4963 

4964 Parameters 

4965 ---------- 

4966 level : int, str, or list of these, default last level 

4967 Level(s) to unstack, can pass level name. 

4968 fill_value : scalar value, default None 

4969 Value to use when replacing NaN values. 

4970 sort : bool, default True 

4971 Sort the level(s) in the resulting MultiIndex columns. This also 

4972 orders the rows of the result: sorted by the remaining levels if 

4973 ``True``, in order of first appearance if ``False``. 

4974 

4975 Returns 

4976 ------- 

4977 DataFrame 

4978 Unstacked Series. 

4979 

4980 See Also 

4981 -------- 

4982 DataFrame.unstack : Pivot the MultiIndex of a DataFrame. 

4983 

4984 Notes 

4985 ----- 

4986 Reference :ref:`the user guide <reshaping.stacking>` for more examples. 

4987 

4988 Examples 

4989 -------- 

4990 >>> s = pd.Series( 

4991 ... [1, 2, 3, 4], 

4992 ... index=pd.MultiIndex.from_product([["one", "two"], ["a", "b"]]), 

4993 ... ) 

4994 >>> s 

4995 one a 1 

4996 b 2 

4997 two a 3 

4998 b 4 

4999 dtype: int64 

5000 

5001 >>> s.unstack(level=-1) 

5002 a b 

5003 one 1 2 

5004 two 3 4 

5005 

5006 >>> s.unstack(level=0) 

5007 one two 

5008 a 1 3 

5009 b 2 4 

5010 """ 

5011 from pandas.core.reshape.reshape import unstack 

5012 

5013 return unstack(self, level, fill_value, sort) 

5014 

5015 # ---------------------------------------------------------------------- 

5016 # function application 

5017 

5018 def map( 

5019 self, 

5020 func: Callable | Mapping | Series | None = None, 

5021 na_action: Literal["ignore"] | None = None, 

5022 engine: Callable | None = None, 

5023 **kwargs, 

5024 ) -> Series: 

5025 """ 

5026 Map values of Series according to an input mapping or function. 

5027 

5028 Used for substituting each value in a Series with another value, 

5029 that may be derived from a function, a ``dict`` or 

5030 a :class:`Series`. 

5031 

5032 Parameters 

5033 ---------- 

5034 func : function, collections.abc.Mapping subclass or Series 

5035 Function or mapping correspondence. 

5036 na_action : {None, 'ignore'}, default None 

5037 If 'ignore', propagate NaN values, without passing them to the 

5038 mapping correspondence. 

5039 engine : decorator, optional 

5040 Choose the execution engine to use to run the function. Only used for 

5041 functions. If ``map`` is called with a mapping or ``Series``, an 

5042 exception will be raised. If ``engine`` is not provided the function will 

5043 be executed by the regular Python interpreter. 

5044 

5045 Options include JIT compilers such as Numba, Bodo or Blosc2, which in some 

5046 cases can speed up the execution. To use an executor you can provide the 

5047 decorators ``numba.jit``, ``numba.njit``, ``bodo.jit`` or ``blosc2.jit``. 

5048 You can also provide the decorator with parameters, like 

5049 ``numba.jit(nogil=True)``. 

5050 

5051 Not all functions can be executed with all execution engines. In general, 

5052 JIT compilers will require type stability in the function (no variable 

5053 should change data type during the execution). And not all pandas and 

5054 NumPy APIs are supported. Check the engine documentation for limitations. 

5055 

5056 .. versionadded:: 3.0.0 

5057 

5058 **kwargs 

5059 Additional keyword arguments to pass as keywords arguments to 

5060 ``func``. 

5061 

5062 .. versionadded:: 3.0.0 

5063 

5064 Returns 

5065 ------- 

5066 Series 

5067 Same index as caller. 

5068 

5069 See Also 

5070 -------- 

5071 Series.apply : For applying more complex functions on a Series. 

5072 Series.replace: Replace values given in `to_replace` with `value`. 

5073 DataFrame.apply : Apply a function row-/column-wise. 

5074 DataFrame.map : Apply a function elementwise on a whole DataFrame. 

5075 

5076 Notes 

5077 ----- 

5078 When ``func`` is a dictionary, values in Series that are not in the 

5079 dictionary (as keys) are converted to ``NaN``. However, if the 

5080 dictionary is a ``dict`` subclass that defines ``__missing__`` (i.e. 

5081 provides a method for default values), then this default is used 

5082 rather than ``NaN``. 

5083 

5084 Examples 

5085 -------- 

5086 >>> s = pd.Series(["cat", "dog", np.nan, "rabbit"]) 

5087 >>> s 

5088 0 cat 

5089 1 dog 

5090 2 NaN 

5091 3 rabbit 

5092 dtype: str 

5093 

5094 ``map`` accepts a ``dict`` or a ``Series``. Values that are not found 

5095 in the ``dict`` are converted to ``NaN``, unless the dict has a default 

5096 value (e.g. ``defaultdict``): 

5097 

5098 >>> s.map({"cat": "kitten", "dog": "puppy"}) 

5099 0 kitten 

5100 1 puppy 

5101 2 NaN 

5102 3 NaN 

5103 dtype: str 

5104 

5105 It also accepts a function: 

5106 

5107 >>> s.map("I am a {}".format) 

5108 0 I am a cat 

5109 1 I am a dog 

5110 2 I am a nan 

5111 3 I am a rabbit 

5112 dtype: str 

5113 

5114 To avoid applying the function to missing values (and keep them as 

5115 ``NaN``) ``na_action='ignore'`` can be used: 

5116 

5117 >>> s.map("I am a {}".format, na_action="ignore") 

5118 0 I am a cat 

5119 1 I am a dog 

5120 2 NaN 

5121 3 I am a rabbit 

5122 dtype: str 

5123 

5124 For categorical data, the function is only applied to the categories: 

5125 

5126 >>> s = pd.Series(list("cabaa")) 

5127 >>> s.map(print) 

5128 c 

5129 a 

5130 b 

5131 a 

5132 a 

5133 0 None 

5134 1 None 

5135 2 None 

5136 3 None 

5137 4 None 

5138 dtype: object 

5139 

5140 >>> s_cat = s.astype("category") 

5141 >>> s_cat.map(print) # function called once per unique category 

5142 a 

5143 b 

5144 c 

5145 0 None 

5146 1 None 

5147 2 None 

5148 3 None 

5149 4 None 

5150 dtype: object 

5151 """ 

5152 if func is None: 

5153 if "arg" in kwargs: 

5154 # `.map(arg=my_func)` 

5155 func = kwargs.pop("arg") 

5156 # https://github.com/pandas-dev/pandas/pull/61264 

5157 warnings.warn( 

5158 "The parameter `arg` has been renamed to `func`, and it " 

5159 "will stop being supported in a future version of pandas.", 

5160 Pandas4Warning, 

5161 stacklevel=find_stack_level(), 

5162 ) 

5163 else: 

5164 raise ValueError("The `func` parameter is required") 

5165 

5166 if engine is not None: 

5167 if not callable(func): 

5168 raise ValueError( 

5169 "The engine argument can only be specified when func is a function" 

5170 ) 

5171 if not hasattr(engine, "__pandas_udf__"): 

5172 raise ValueError(f"Not a valid engine: {engine!r}") 

5173 result = engine.__pandas_udf__.map( # type: ignore[attr-defined] 

5174 data=self, 

5175 func=func, 

5176 args=(), 

5177 kwargs=kwargs, 

5178 decorator=engine, 

5179 skip_na=na_action == "ignore", 

5180 ) 

5181 if not isinstance(result, Series): 

5182 result = Series(result, index=self.index, name=self.name) 

5183 return result.__finalize__(self, method="map") 

5184 

5185 if callable(func): 

5186 func = functools.partial(func, **kwargs) 

5187 new_values = self._map_values(func, na_action=na_action) 

5188 return self._constructor(new_values, index=self.index, copy=False).__finalize__( 

5189 self, method="map" 

5190 ) 

5191 

5192 def _gotitem(self, key, ndim, subset=None) -> Self: 

5193 """ 

5194 Sub-classes to define. Return a sliced object. 

5195 

5196 Parameters 

5197 ---------- 

5198 key : string / list of selections 

5199 ndim : {1, 2} 

5200 Requested ndim of result. 

5201 subset : object, default None 

5202 Subset to act on. 

5203 """ 

5204 return self 

5205 

5206 def aggregate( 

5207 self, func=None, axis: Axis = 0, *args, **kwargs 

5208 ) -> DataFrame | Series: 

5209 """ 

5210 Aggregate using one or more operations over the specified axis. 

5211 

5212 This method applies one or more aggregation functions to the Series 

5213 and returns a scalar, Series, or DataFrame depending on the 

5214 function(s) provided. 

5215 

5216 Parameters 

5217 ---------- 

5218 func : function, str, list or dict 

5219 Function to use for aggregating the data. If a function, must either 

5220 work when passed a Series or when passed to Series.apply. 

5221 

5222 Accepted combinations are: 

5223 

5224 - function 

5225 - string function name 

5226 - list of functions and/or function names, e.g. ``[np.sum, 'mean']`` 

5227 - dict of axis labels -> functions, function names or list of such. 

5228 axis : {0 or 'index'} 

5229 Unused. Parameter needed for compatibility with DataFrame. 

5230 *args 

5231 Positional arguments to pass to `func`. 

5232 **kwargs 

5233 Keyword arguments to pass to `func`. 

5234 

5235 Returns 

5236 ------- 

5237 scalar, Series or DataFrame 

5238 The return can be: 

5239 

5240 * scalar : when Series.agg is called with single function 

5241 * Series : when DataFrame.agg is called with a single function 

5242 * DataFrame : when DataFrame.agg is called with several functions 

5243 

5244 See Also 

5245 -------- 

5246 Series.apply : Invoke function on a Series. 

5247 Series.transform : Transform function producing a Series with like indexes. 

5248 

5249 Notes 

5250 ----- 

5251 The aggregation operations are always performed over an axis, either the 

5252 index (default) or the column axis. This behavior is different from 

5253 `numpy` aggregation functions (`mean`, `median`, `prod`, `sum`, `std`, 

5254 `var`), where the default is to compute the aggregation of the flattened 

5255 array, e.g., ``numpy.mean(arr_2d)`` as opposed to 

5256 ``numpy.mean(arr_2d, axis=0)``. 

5257 

5258 `agg` is an alias for `aggregate`. Use the alias. 

5259 

5260 Functions that mutate the passed object can produce unexpected 

5261 behavior or errors and are not supported. See :ref:`gotchas.udf-mutation` 

5262 for more details. 

5263 

5264 A passed user-defined-function will be passed a Series for evaluation. 

5265 

5266 If ``func`` defines an index relabeling, ``axis`` must be ``0`` or ``index``. 

5267 

5268 Examples 

5269 -------- 

5270 >>> s = pd.Series([1, 2, 3, 4]) 

5271 >>> s 

5272 0 1 

5273 1 2 

5274 2 3 

5275 3 4 

5276 dtype: int64 

5277 

5278 >>> s.agg("min") 

5279 1 

5280 

5281 >>> s.agg(["min", "max"]) 

5282 min 1 

5283 max 4 

5284 dtype: int64 

5285 """ 

5286 

5287 # Validate the axis parameter 

5288 self._get_axis_number(axis) 

5289 

5290 # if func is None, will switch to user-provided "named aggregation" kwargs 

5291 if func is None: 

5292 func = dict(kwargs.items()) 

5293 

5294 op = SeriesApply(self, func, args=args, kwargs=kwargs) 

5295 result = op.agg() 

5296 return result 

5297 

5298 agg = aggregate 

5299 

5300 def transform( 

5301 self, func: AggFuncType, axis: Axis = 0, *args, **kwargs 

5302 ) -> DataFrame | Series: 

5303 """ 

5304 Call ``func`` on self producing a Series with the same axis shape as self. 

5305 

5306 Unlike ``agg``, which can return a scalar or a smaller result, 

5307 ``transform`` must return a result that is the same size as the input. 

5308 This makes it suitable for element-wise operations. 

5309 

5310 Parameters 

5311 ---------- 

5312 func : function, str, list-like or dict-like 

5313 Function to use for transforming the data. If a function, must either 

5314 work when passed a Series or when passed to Series.apply. If func 

5315 is both list-like and dict-like, dict-like behavior takes precedence. 

5316 

5317 Accepted combinations are: 

5318 

5319 - function 

5320 - string function name 

5321 - list-like of functions and/or function names, e.g. ``[np.exp, 'sqrt']`` 

5322 - dict-like of axis labels -> functions, function names or list-like of such 

5323 

5324 axis : {0 or 'index'} 

5325 Unused. Parameter needed for compatibility with DataFrame. 

5326 

5327 *args 

5328 Positional arguments to pass to `func`. 

5329 **kwargs 

5330 Keyword arguments to pass to `func`. 

5331 

5332 Returns 

5333 ------- 

5334 Series 

5335 A Series that must have the same length as self. 

5336 

5337 Raises 

5338 ------ 

5339 ValueError : If the returned Series has a different length than self. 

5340 

5341 See Also 

5342 -------- 

5343 Series.agg : Only perform aggregating type operations. 

5344 Series.apply : Invoke function on a Series. 

5345 

5346 Notes 

5347 ----- 

5348 Functions that mutate the passed object can produce unexpected 

5349 behavior or errors and are not supported. See :ref:`gotchas.udf-mutation` 

5350 for more details. 

5351 

5352 Examples 

5353 -------- 

5354 >>> df = pd.DataFrame({"A": range(3), "B": range(1, 4)}) 

5355 >>> df 

5356 A B 

5357 0 0 1 

5358 1 1 2 

5359 2 2 3 

5360 >>> df.transform(lambda x: x + 1) 

5361 A B 

5362 0 1 2 

5363 1 2 3 

5364 2 3 4 

5365 

5366 Even though the resulting Series must have the same length as the 

5367 input Series, it is possible to provide several input functions: 

5368 

5369 >>> s = pd.Series(range(3)) 

5370 >>> s 

5371 0 0 

5372 1 1 

5373 2 2 

5374 dtype: int64 

5375 >>> s.transform([np.sqrt, np.exp]) 

5376 sqrt exp 

5377 0 0.000000 1.000000 

5378 1 1.000000 2.718282 

5379 2 1.414214 7.389056 

5380 

5381 You can call transform on a GroupBy object: 

5382 

5383 >>> df = pd.DataFrame( 

5384 ... { 

5385 ... "Date": [ 

5386 ... "2015-05-08", 

5387 ... "2015-05-07", 

5388 ... "2015-05-06", 

5389 ... "2015-05-05", 

5390 ... "2015-05-08", 

5391 ... "2015-05-07", 

5392 ... "2015-05-06", 

5393 ... "2015-05-05", 

5394 ... ], 

5395 ... "Data": [5, 8, 6, 1, 50, 100, 60, 120], 

5396 ... } 

5397 ... ) 

5398 >>> df 

5399 Date Data 

5400 0 2015-05-08 5 

5401 1 2015-05-07 8 

5402 2 2015-05-06 6 

5403 3 2015-05-05 1 

5404 4 2015-05-08 50 

5405 5 2015-05-07 100 

5406 6 2015-05-06 60 

5407 7 2015-05-05 120 

5408 >>> df.groupby("Date")["Data"].transform("sum") 

5409 0 55 

5410 1 108 

5411 2 66 

5412 3 121 

5413 4 55 

5414 5 108 

5415 6 66 

5416 7 121 

5417 Name: Data, dtype: int64 

5418 

5419 >>> df = pd.DataFrame( 

5420 ... { 

5421 ... "c": [1, 1, 1, 2, 2, 2, 2], 

5422 ... "type": ["m", "n", "o", "m", "m", "n", "n"], 

5423 ... } 

5424 ... ) 

5425 >>> df 

5426 c type 

5427 0 1 m 

5428 1 1 n 

5429 2 1 o 

5430 3 2 m 

5431 4 2 m 

5432 5 2 n 

5433 6 2 n 

5434 >>> df["size"] = df.groupby("c")["type"].transform(len) 

5435 >>> df 

5436 c type size 

5437 0 1 m 3 

5438 1 1 n 3 

5439 2 1 o 3 

5440 3 2 m 4 

5441 4 2 m 4 

5442 5 2 n 4 

5443 6 2 n 4 

5444 """ 

5445 # Validate axis argument 

5446 self._get_axis_number(axis) 

5447 ser = self.copy(deep=False) 

5448 result = SeriesApply(ser, func=func, args=args, kwargs=kwargs).transform() 

5449 return result 

5450 

5451 def apply( 

5452 self, 

5453 func: AggFuncType, 

5454 args: tuple[Any, ...] = (), 

5455 *, 

5456 by_row: Literal[False, "compat"] = "compat", 

5457 **kwargs, 

5458 ) -> DataFrame | Series: 

5459 """ 

5460 Invoke function on values of Series. 

5461 

5462 Can be ufunc (a NumPy function that applies to the entire Series) 

5463 or a Python function that only works on single values. 

5464 

5465 Parameters 

5466 ---------- 

5467 func : function 

5468 Python function or NumPy ufunc to apply. 

5469 args : tuple 

5470 Positional arguments passed to func after the series value. 

5471 by_row : False or "compat", default "compat" 

5472 If ``"compat"`` and func is a callable, func will be passed each element of 

5473 the Series, like ``Series.map``. If func is a list or dict of 

5474 callables, will first try to translate each func into pandas methods. If 

5475 that doesn't work, will try call to apply again with ``by_row="compat"`` 

5476 and if that fails, will call apply again with ``by_row=False`` 

5477 (backward compatible). 

5478 If False, the func will be passed the whole Series at once. 

5479 

5480 ``by_row`` has no effect when ``func`` is a string. 

5481 

5482 .. versionadded:: 2.1.0 

5483 **kwargs 

5484 Additional keyword arguments passed to func. 

5485 

5486 Returns 

5487 ------- 

5488 Series or DataFrame 

5489 If func returns a Series object the result will be a DataFrame. 

5490 

5491 See Also 

5492 -------- 

5493 Series.map: For element-wise operations. 

5494 Series.agg: Only perform aggregating type operations. 

5495 Series.transform: Only perform transforming type operations. 

5496 

5497 Notes 

5498 ----- 

5499 Functions that mutate the passed object can produce unexpected 

5500 behavior or errors and are not supported. See :ref:`gotchas.udf-mutation` 

5501 for more details. 

5502 

5503 Examples 

5504 -------- 

5505 Create a series with typical summer temperatures for each city. 

5506 

5507 >>> s = pd.Series([20, 21, 12], index=["London", "New York", "Helsinki"]) 

5508 >>> s 

5509 London 20 

5510 New York 21 

5511 Helsinki 12 

5512 dtype: int64 

5513 

5514 Square the values by defining a function and passing it as an 

5515 argument to ``apply()``. 

5516 

5517 >>> def square(x): 

5518 ... return x**2 

5519 >>> s.apply(square) 

5520 London 400 

5521 New York 441 

5522 Helsinki 144 

5523 dtype: int64 

5524 

5525 Square the values by passing an anonymous function as an 

5526 argument to ``apply()``. 

5527 

5528 >>> s.apply(lambda x: x**2) 

5529 London 400 

5530 New York 441 

5531 Helsinki 144 

5532 dtype: int64 

5533 

5534 Define a custom function that needs additional positional 

5535 arguments and pass these additional arguments using the 

5536 ``args`` keyword. 

5537 

5538 >>> def subtract_custom_value(x, custom_value): 

5539 ... return x - custom_value 

5540 

5541 >>> s.apply(subtract_custom_value, args=(5,)) 

5542 London 15 

5543 New York 16 

5544 Helsinki 7 

5545 dtype: int64 

5546 

5547 Define a custom function that takes keyword arguments 

5548 and pass these arguments to ``apply``. 

5549 

5550 >>> def add_custom_values(x, **kwargs): 

5551 ... for month in kwargs: 

5552 ... x += kwargs[month] 

5553 ... return x 

5554 

5555 >>> s.apply(add_custom_values, june=30, july=20, august=25) 

5556 London 95 

5557 New York 96 

5558 Helsinki 87 

5559 dtype: int64 

5560 

5561 Use a function from the Numpy library. 

5562 

5563 >>> s.apply(np.log) 

5564 London 2.995732 

5565 New York 3.044522 

5566 Helsinki 2.484907 

5567 dtype: float64 

5568 """ 

5569 return SeriesApply( 

5570 self, 

5571 func, 

5572 by_row=by_row, 

5573 args=args, 

5574 kwargs=kwargs, 

5575 ).apply() 

5576 

5577 def _reindex_indexer( 

5578 self, 

5579 new_index: Index | None, 

5580 indexer: npt.NDArray[np.intp] | None, 

5581 ) -> Series: 

5582 # Note: new_index is None iff indexer is None 

5583 # if not None, indexer is np.intp 

5584 if indexer is None and ( 

5585 new_index is None or new_index.names == self.index.names 

5586 ): 

5587 return self.copy(deep=False) 

5588 

5589 new_values = algorithms.take_nd( 

5590 self._values, indexer, allow_fill=True, fill_value=None 

5591 ) 

5592 return self._constructor(new_values, index=new_index, copy=False) 

5593 

5594 def _needs_reindex_multi(self, axes, method, level) -> bool: 

5595 """ 

5596 Check if we do need a multi reindex; this is for compat with 

5597 higher dims. 

5598 """ 

5599 return False 

5600 

5601 @overload 

5602 def rename( 

5603 self, 

5604 index: Renamer | Hashable | None = ..., 

5605 *, 

5606 axis: Axis | None = ..., 

5607 copy: bool | lib.NoDefault = ..., 

5608 inplace: Literal[True], 

5609 level: Level | None = ..., 

5610 errors: IgnoreRaise = ..., 

5611 ) -> Series | None: ... 

5612 

5613 @overload 

5614 def rename( 

5615 self, 

5616 index: Renamer | Hashable | None = ..., 

5617 *, 

5618 axis: Axis | None = ..., 

5619 copy: bool | lib.NoDefault = ..., 

5620 inplace: Literal[False] = ..., 

5621 level: Level | None = ..., 

5622 errors: IgnoreRaise = ..., 

5623 ) -> Series: ... 

5624 

5625 def rename( 

5626 self, 

5627 index: Renamer | Hashable | None = None, 

5628 *, 

5629 axis: Axis | None = None, 

5630 copy: bool | lib.NoDefault = lib.no_default, 

5631 inplace: bool | lib.NoDefault = lib.no_default, 

5632 level: Level | None = None, 

5633 errors: IgnoreRaise = "ignore", 

5634 ) -> Series | None: 

5635 """ 

5636 Alter Series index labels or name. 

5637 

5638 Function / dict values must be unique (1-to-1). Labels not contained in 

5639 a dict / Series will be left as-is. Extra labels listed don't throw an 

5640 error. 

5641 

5642 Alternatively, change ``Series.name`` with a scalar value. 

5643 

5644 See the :ref:`user guide <basics.rename>` for more. 

5645 

5646 Parameters 

5647 ---------- 

5648 index : scalar, hashable sequence, dict-like or function optional 

5649 Functions or dict-like are transformations to apply to 

5650 the index. 

5651 Scalar or hashable sequence-like will alter the ``Series.name`` 

5652 attribute. 

5653 axis : {0 or 'index'} 

5654 Unused. Parameter needed for compatibility with DataFrame. 

5655 copy : bool, default False 

5656 This keyword is now ignored; changing its value will have no 

5657 impact on the method. 

5658 

5659 .. deprecated:: 3.0.0 

5660 

5661 This keyword is ignored and will be removed in pandas 4.0. Since 

5662 pandas 3.0, this method always returns a new object using a lazy 

5663 copy mechanism that defers copies until necessary 

5664 (Copy-on-Write). See the `user guide on Copy-on-Write 

5665 <https://pandas.pydata.org/docs/dev/user_guide/migration.html>`__ 

5666 for more details. 

5667 

5668 inplace : bool, default False 

5669 Whether to return a new Series. If True the value of copy is ignored. 

5670 

5671 .. deprecated:: 3.1.0 

5672 

5673 This keyword is deprecated and will be removed in pandas 4.0. 

5674 See the `whatsnew note on PDEP-8 

5675 <https://pandas.pydata.org/docs/dev/whatsnew/v3.1.0.html#deprecation-inplace>`__ 

5676 for more details. 

5677 

5678 level : int or level name, default None 

5679 In case of MultiIndex, only rename labels in the specified level. 

5680 errors : {'ignore', 'raise'}, default 'ignore' 

5681 If 'raise', raise `KeyError` when a `dict-like mapper` or 

5682 `index` contains labels that are not present in the index being transformed. 

5683 If 'ignore', existing keys will be renamed and extra keys will be ignored. 

5684 

5685 Returns 

5686 ------- 

5687 Series 

5688 A shallow copy with index labels or name altered, or the same object 

5689 if ``inplace=True`` and index is not a dict or callable else None. 

5690 

5691 See Also 

5692 -------- 

5693 DataFrame.rename : Corresponding DataFrame method. 

5694 Series.rename_axis : Set the name of the axis. 

5695 

5696 Examples 

5697 -------- 

5698 >>> s = pd.Series([1, 2, 3]) 

5699 >>> s 

5700 0 1 

5701 1 2 

5702 2 3 

5703 dtype: int64 

5704 >>> s.rename("my_name") # scalar, changes Series.name 

5705 0 1 

5706 1 2 

5707 2 3 

5708 Name: my_name, dtype: int64 

5709 >>> s.rename(lambda x: x**2) # function, changes labels 

5710 0 1 

5711 1 2 

5712 4 3 

5713 dtype: int64 

5714 >>> s.rename({1: 3, 2: 5}) # mapping, changes labels 

5715 0 1 

5716 3 2 

5717 5 3 

5718 dtype: int64 

5719 """ 

5720 inplace = self._check_inplace_deprecation(inplace, "rename") 

5721 self._check_copy_deprecation(copy) 

5722 if axis is not None: 

5723 # Make sure we raise if an invalid 'axis' is passed. 

5724 axis = self._get_axis_number(axis) 

5725 

5726 if callable(index) or is_dict_like(index): 

5727 # error: Argument 1 to "_rename" of "NDFrame" has incompatible 

5728 # type "Union[Union[Mapping[Any, Hashable], Callable[[Any], 

5729 # Hashable]], Hashable, None]"; expected "Union[Mapping[Any, 

5730 # Hashable], Callable[[Any], Hashable], None]" 

5731 return super()._rename( 

5732 index, # type: ignore[arg-type] 

5733 inplace=inplace, 

5734 level=level, 

5735 errors=errors, 

5736 ) 

5737 else: 

5738 return self._set_name(index, inplace=inplace) 

5739 

5740 def set_axis( 

5741 self, 

5742 labels, 

5743 *, 

5744 axis: Axis = 0, 

5745 copy: bool | lib.NoDefault = lib.no_default, 

5746 ) -> Series: 

5747 """ 

5748 Assign desired index to given axis. 

5749 

5750 Indexes for row labels can be changed by assigning a list-like or Index. 

5751 

5752 Parameters 

5753 ---------- 

5754 labels : list-like or Index 

5755 The values for the new index. 

5756 axis : {0 or 'index'}, default 0 

5757 The axis to update. The value 0 identifies the rows. For `Series` 

5758 this parameter is unused and defaults to 0. 

5759 copy : bool, default False 

5760 This keyword is now ignored; changing its value will have no 

5761 impact on the method. 

5762 

5763 .. deprecated:: 3.0.0 

5764 

5765 This keyword is ignored and will be removed in pandas 4.0. Since 

5766 pandas 3.0, this method always returns a new object using a lazy 

5767 copy mechanism that defers copies until necessary 

5768 (Copy-on-Write). See the `user guide on Copy-on-Write 

5769 <https://pandas.pydata.org/docs/dev/user_guide/migration.html>`__ 

5770 for more details. 

5771 

5772 Returns 

5773 ------- 

5774 Series 

5775 A shallow copy of the object with axis altered to the given index. 

5776 

5777 See Also 

5778 -------- 

5779 Series.rename_axis : Alter the name of the index. 

5780 

5781 Examples 

5782 -------- 

5783 >>> s = pd.Series([1, 2, 3]) 

5784 >>> s 

5785 0 1 

5786 1 2 

5787 2 3 

5788 dtype: int64 

5789 >>> s.set_axis(["a", "b", "c"], axis=0) 

5790 a 1 

5791 b 2 

5792 c 3 

5793 dtype: int64 

5794 """ 

5795 

5796 return super().set_axis(labels, axis=axis, copy=copy) 

5797 

5798 # error: Cannot determine type of 'reindex' 

5799 

5800 def reindex( # type: ignore[override] 

5801 self, 

5802 index=None, 

5803 *, 

5804 axis: Axis | None = None, 

5805 method: ReindexMethod | None = None, 

5806 copy: bool | lib.NoDefault = lib.no_default, 

5807 level: Level | None = None, 

5808 fill_value: Scalar | None = None, 

5809 limit: int | None = None, 

5810 tolerance=None, 

5811 ) -> Series: 

5812 """ 

5813 Conform Series to new index with optional filling logic. 

5814 

5815 Places NA/NaN in locations having no value in the previous index. A new object 

5816 is produced unless the new index is equivalent to the current one and 

5817 ``copy=False``. 

5818 

5819 Parameters 

5820 ---------- 

5821 index : scalar, list-like, dict-like or function, optional 

5822 A scalar, list-like, dict-like or functions transformations to 

5823 apply to that axis' values. 

5824 axis : {0 or 'index'}, default 0 

5825 The axis to rename. For `Series` this parameter is unused and defaults to 0. 

5826 method : {None, 'backfill'/'bfill', 'pad'/'ffill', 'nearest'} 

5827 Method to use for filling holes in reindexed DataFrame. 

5828 Please note: this is only applicable to DataFrames/Series with a 

5829 monotonically increasing/decreasing index. 

5830 Filling is based on the position of each new label relative to the 

5831 existing labels. For example, with ``method='ffill'`` and a 

5832 monotonically increasing index, a new label is filled from the 

5833 nearest existing label that sorts before it. 

5834 

5835 * None (default): don't fill gaps 

5836 * pad / ffill: Propagate last valid observation forward to next 

5837 valid. 

5838 * backfill / bfill: Use next valid observation to fill gap. 

5839 * nearest: Use nearest valid observations to fill gap. 

5840 

5841 copy : bool, default False 

5842 This keyword is now ignored; changing its value will have no 

5843 impact on the method. 

5844 

5845 .. deprecated:: 3.0.0 

5846 

5847 This keyword is ignored and will be removed in pandas 4.0. Since 

5848 pandas 3.0, this method always returns a new object using a lazy 

5849 copy mechanism that defers copies until necessary 

5850 (Copy-on-Write). See the `user guide on Copy-on-Write 

5851 <https://pandas.pydata.org/docs/dev/user_guide/migration.html>`__ 

5852 for more details. 

5853 

5854 level : int or name 

5855 Match index values on the specified level of a MultiIndex. 

5856 The MultiIndex may be on either the calling object or the 

5857 target index; using ``level`` when both are MultiIndexes is 

5858 ambiguous and raises a ``TypeError``. The new labels are 

5859 aligned against the values of that single level while the 

5860 other levels are left unchanged; passing a flat index with 

5861 ``level`` does not form the Cartesian product of the 

5862 remaining levels. See :ref:`advanced.advanced_reindex` for 

5863 the intended use. 

5864 fill_value : scalar, default np.nan 

5865 Value to use for missing values. Defaults to NaN, but can be any 

5866 "compatible" value. 

5867 limit : int, default None 

5868 Maximum number of consecutive elements to forward or backward fill. 

5869 tolerance : optional 

5870 Maximum distance between original and new labels for inexact 

5871 matches. The values of the index at the matching locations most 

5872 satisfy the equation ``abs(index[indexer] - target) <= tolerance``. 

5873 

5874 Tolerance may be a scalar value, which applies the same tolerance 

5875 to all values, or list-like, which applies variable tolerance per 

5876 element. List-like includes list, tuple, array, Series, and must be 

5877 the same size as the index and its dtype must exactly match the 

5878 index's type. 

5879 

5880 Returns 

5881 ------- 

5882 Series 

5883 Series with changed index. 

5884 

5885 See Also 

5886 -------- 

5887 DataFrame.set_index : Set row labels. 

5888 DataFrame.reset_index : Remove row labels or move them to new columns. 

5889 DataFrame.reindex_like : Change to same indices as other DataFrame. 

5890 

5891 Examples 

5892 -------- 

5893 ``DataFrame.reindex`` supports two calling conventions 

5894 

5895 * ``(index=index_labels, columns=column_labels, ...)`` 

5896 * ``(labels, axis={'index', 'columns'}, ...)`` 

5897 

5898 We *highly* recommend using keyword arguments to clarify your 

5899 intent. 

5900 

5901 Create a DataFrame with some fictional data. 

5902 

5903 >>> index = ["Firefox", "Chrome", "Safari", "IE10", "Konqueror"] 

5904 >>> columns = ["http_status", "response_time"] 

5905 >>> df = pd.DataFrame( 

5906 ... [[200, 0.04], [200, 0.02], [404, 0.07], [404, 0.08], [301, 1.0]], 

5907 ... columns=columns, 

5908 ... index=index, 

5909 ... ) 

5910 >>> df 

5911 http_status response_time 

5912 Firefox 200 0.04 

5913 Chrome 200 0.02 

5914 Safari 404 0.07 

5915 IE10 404 0.08 

5916 Konqueror 301 1.00 

5917 

5918 Create a new index and reindex the DataFrame. By default 

5919 values in the new index that do not have corresponding 

5920 records in the DataFrame are assigned ``NaN``. 

5921 

5922 >>> new_index = ["Safari", "Iceweasel", "Comodo Dragon", "IE10", "Chrome"] 

5923 >>> df.reindex(new_index) 

5924 http_status response_time 

5925 Safari 404.0 0.07 

5926 Iceweasel NaN NaN 

5927 Comodo Dragon NaN NaN 

5928 IE10 404.0 0.08 

5929 Chrome 200.0 0.02 

5930 

5931 We can fill in the missing values by passing a value to 

5932 the keyword ``fill_value``. Because the index is not monotonically 

5933 increasing or decreasing, we cannot use arguments to the keyword 

5934 ``method`` to fill the ``NaN`` values. 

5935 

5936 >>> df.reindex(new_index, fill_value=0) 

5937 http_status response_time 

5938 Safari 404 0.07 

5939 Iceweasel 0 0.00 

5940 Comodo Dragon 0 0.00 

5941 IE10 404 0.08 

5942 Chrome 200 0.02 

5943 

5944 We can also reindex the columns. 

5945 

5946 >>> df.reindex(columns=["http_status", "user_agent"]) 

5947 http_status user_agent 

5948 Firefox 200 NaN 

5949 Chrome 200 NaN 

5950 Safari 404 NaN 

5951 IE10 404 NaN 

5952 Konqueror 301 NaN 

5953 

5954 Or we can use "axis-style" keyword arguments 

5955 

5956 >>> df.reindex(["http_status", "user_agent"], axis="columns") 

5957 http_status user_agent 

5958 Firefox 200 NaN 

5959 Chrome 200 NaN 

5960 Safari 404 NaN 

5961 IE10 404 NaN 

5962 Konqueror 301 NaN 

5963 

5964 To further illustrate the filling functionality in 

5965 ``reindex``, we will create a DataFrame with a 

5966 monotonically increasing index (for example, a sequence 

5967 of dates). 

5968 

5969 >>> date_index = pd.date_range("1/1/2010", periods=6, freq="D") 

5970 >>> df2 = pd.DataFrame( 

5971 ... {"prices": [100, 101, np.nan, 100, 89, 88]}, index=date_index 

5972 ... ) 

5973 >>> df2 

5974 prices 

5975 2010-01-01 100.0 

5976 2010-01-02 101.0 

5977 2010-01-03 NaN 

5978 2010-01-04 100.0 

5979 2010-01-05 89.0 

5980 2010-01-06 88.0 

5981 

5982 Suppose we decide to expand the DataFrame to cover a wider 

5983 date range. 

5984 

5985 >>> date_index2 = pd.date_range("12/29/2009", periods=10, freq="D") 

5986 >>> df2.reindex(date_index2) 

5987 prices 

5988 2009-12-29 NaN 

5989 2009-12-30 NaN 

5990 2009-12-31 NaN 

5991 2010-01-01 100.0 

5992 2010-01-02 101.0 

5993 2010-01-03 NaN 

5994 2010-01-04 100.0 

5995 2010-01-05 89.0 

5996 2010-01-06 88.0 

5997 2010-01-07 NaN 

5998 

5999 The index entries that did not have a value in the original data frame 

6000 (for example, '2009-12-29') are by default filled with ``NaN``. 

6001 If desired, we can fill in the missing values using one of several 

6002 options. 

6003 

6004 For example, to back-propagate the last valid value to fill the ``NaN`` 

6005 values, pass ``bfill`` as an argument to the ``method`` keyword. 

6006 

6007 >>> df2.reindex(date_index2, method="bfill") 

6008 prices 

6009 2009-12-29 100.0 

6010 2009-12-30 100.0 

6011 2009-12-31 100.0 

6012 2010-01-01 100.0 

6013 2010-01-02 101.0 

6014 2010-01-03 NaN 

6015 2010-01-04 100.0 

6016 2010-01-05 89.0 

6017 2010-01-06 88.0 

6018 2010-01-07 NaN 

6019 

6020 Please note that the ``NaN`` value present in the original DataFrame 

6021 (at index value 2010-01-03) will not be filled by any of the 

6022 value propagation schemes. This is because filling while reindexing 

6023 does not look at DataFrame values, but only compares the original and 

6024 desired indexes. If you do want to fill in the ``NaN`` values present 

6025 in the original DataFrame, use the ``fillna()`` method. 

6026 

6027 Because ``method="bfill"`` fills each new label from the next entry 

6028 present in the original index, the trailing entry at 2010-01-07 stays 

6029 ``NaN``: there is no original index entry after it. Conversely, 

6030 ``method="ffill"`` would leave the leading entries (before the first 

6031 original index entry) unfilled. 

6032 

6033 See the :ref:`user guide <basics.reindexing>` for more. 

6034 """ 

6035 return super().reindex( 

6036 index=index, 

6037 method=method, 

6038 level=level, 

6039 fill_value=fill_value, 

6040 limit=limit, 

6041 tolerance=tolerance, 

6042 copy=copy, 

6043 ) 

6044 

6045 @overload # type: ignore[override] 

6046 def rename_axis( 

6047 self, 

6048 mapper: IndexLabel | lib.NoDefault = ..., 

6049 *, 

6050 index=..., 

6051 axis: Axis = ..., 

6052 copy: bool | lib.NoDefault = ..., 

6053 inplace: Literal[True], 

6054 ) -> None: ... 

6055 

6056 @overload 

6057 def rename_axis( 

6058 self, 

6059 mapper: IndexLabel | lib.NoDefault = ..., 

6060 *, 

6061 index=..., 

6062 axis: Axis = ..., 

6063 copy: bool | lib.NoDefault = ..., 

6064 inplace: Literal[False] = ..., 

6065 ) -> Self: ... 

6066 

6067 @overload 

6068 def rename_axis( 

6069 self, 

6070 mapper: IndexLabel | lib.NoDefault = ..., 

6071 *, 

6072 index=..., 

6073 axis: Axis = ..., 

6074 copy: bool | lib.NoDefault = ..., 

6075 inplace: bool | lib.NoDefault = ..., 

6076 ) -> Self | None: ... 

6077 

6078 def rename_axis( 

6079 self, 

6080 mapper: IndexLabel | lib.NoDefault = lib.no_default, 

6081 *, 

6082 index=lib.no_default, 

6083 axis: Axis = 0, 

6084 copy: bool | lib.NoDefault = lib.no_default, 

6085 inplace: bool | lib.NoDefault = lib.no_default, 

6086 ) -> Self | None: 

6087 """ 

6088 Set the name of the axis for the index. 

6089 

6090 This method sets or changes the name of the index (axis) of the 

6091 Series. It can accept a scalar, list-like, or function to rename 

6092 the axis. 

6093 

6094 Parameters 

6095 ---------- 

6096 mapper : scalar, list-like, optional 

6097 Value to set the axis name attribute. 

6098 

6099 Use either ``mapper`` and ``axis`` to 

6100 specify the axis to target with ``mapper``, or ``index``. 

6101 

6102 index : scalar, list-like, dict-like or function, optional 

6103 A scalar, list-like, dict-like or functions transformations to 

6104 apply to that axis' values. 

6105 axis : {0 or 'index'}, default 0 

6106 The axis to rename. For `Series` this parameter is unused and defaults to 0. 

6107 copy : bool, default False 

6108 This keyword is now ignored; changing its value will have no 

6109 impact on the method. 

6110 

6111 .. deprecated:: 3.0.0 

6112 

6113 This keyword is ignored and will be removed in pandas 4.0. Since 

6114 pandas 3.0, this method always returns a new object using a lazy 

6115 copy mechanism that defers copies until necessary 

6116 (Copy-on-Write). See the `user guide on Copy-on-Write 

6117 <https://pandas.pydata.org/docs/dev/user_guide/migration.html>`__ 

6118 for more details. 

6119 

6120 inplace : bool, default False 

6121 Modifies the object directly, instead of creating a new Series 

6122 or DataFrame. 

6123 

6124 .. deprecated:: 3.1.0 

6125 

6126 This keyword is deprecated and will be removed in pandas 4.0. 

6127 See the `whatsnew note on PDEP-8 

6128 <https://pandas.pydata.org/docs/dev/whatsnew/v3.1.0.html#deprecation-inplace>`__ 

6129 for more details. 

6130 

6131 Returns 

6132 ------- 

6133 Series, or None 

6134 The same type as the caller or None if ``inplace=True``. 

6135 

6136 See Also 

6137 -------- 

6138 Series.rename : Alter Series index labels or name. 

6139 DataFrame.rename : Alter DataFrame index labels or name. 

6140 Index.rename : Set new names on index. 

6141 

6142 Examples 

6143 -------- 

6144 

6145 >>> s = pd.Series(["dog", "cat", "monkey"]) 

6146 >>> s 

6147 0 dog 

6148 1 cat 

6149 2 monkey 

6150 dtype: str 

6151 >>> s.rename_axis("animal") 

6152 animal 

6153 0 dog 

6154 1 cat 

6155 2 monkey 

6156 dtype: str 

6157 """ 

6158 inplace = self._check_inplace_deprecation(inplace, "rename_axis") 

6159 

6160 return super().rename_axis( 

6161 mapper=mapper, 

6162 index=index, 

6163 axis=axis, 

6164 inplace=inplace, 

6165 copy=copy, 

6166 ) 

6167 

6168 @overload 

6169 def drop( 

6170 self, 

6171 labels: IndexLabel | ListLike = ..., 

6172 *, 

6173 axis: Axis = ..., 

6174 index: IndexLabel | ListLike = ..., 

6175 columns: IndexLabel | ListLike = ..., 

6176 level: Level | None = ..., 

6177 inplace: Literal[True], 

6178 errors: IgnoreRaise = ..., 

6179 ) -> None: ... 

6180 

6181 @overload 

6182 def drop( 

6183 self, 

6184 labels: IndexLabel | ListLike = ..., 

6185 *, 

6186 axis: Axis = ..., 

6187 index: IndexLabel | ListLike = ..., 

6188 columns: IndexLabel | ListLike = ..., 

6189 level: Level | None = ..., 

6190 inplace: Literal[False] = ..., 

6191 errors: IgnoreRaise = ..., 

6192 ) -> Series: ... 

6193 

6194 @overload 

6195 def drop( 

6196 self, 

6197 labels: IndexLabel | ListLike = ..., 

6198 *, 

6199 axis: Axis = ..., 

6200 index: IndexLabel | ListLike = ..., 

6201 columns: IndexLabel | ListLike = ..., 

6202 level: Level | None = ..., 

6203 inplace: bool | lib.NoDefault = ..., 

6204 errors: IgnoreRaise = ..., 

6205 ) -> Series | None: ... 

6206 

6207 def drop( 

6208 self, 

6209 labels: IndexLabel | ListLike = None, 

6210 *, 

6211 axis: Axis = 0, 

6212 index: IndexLabel | ListLike = None, 

6213 columns: IndexLabel | ListLike = None, 

6214 level: Level | None = None, 

6215 inplace: bool | lib.NoDefault = lib.no_default, 

6216 errors: IgnoreRaise = "raise", 

6217 ) -> Series | None: 

6218 """ 

6219 Return Series with specified index labels removed. 

6220 

6221 Remove elements of a Series based on specifying the index labels. 

6222 When using a multi-index, labels on different levels can be removed 

6223 by specifying the level. 

6224 

6225 Parameters 

6226 ---------- 

6227 labels : single label or list-like 

6228 Index labels to drop. 

6229 axis : {0 or 'index'} 

6230 Unused. Parameter needed for compatibility with DataFrame. 

6231 index : single label or list-like 

6232 Redundant for application on Series, but 'index' can be used instead 

6233 of 'labels'. 

6234 columns : single label or list-like 

6235 No change is made to the Series; use 'index' or 'labels' instead. 

6236 level : int or level name, optional 

6237 For MultiIndex, level for which the labels will be removed. 

6238 inplace : bool, default False 

6239 If True, do operation inplace and return None. 

6240 

6241 .. deprecated:: 3.1.0 

6242 

6243 This keyword is deprecated and will be removed in pandas 4.0. 

6244 See the `whatsnew note on PDEP-8 

6245 <https://pandas.pydata.org/docs/dev/whatsnew/v3.1.0.html#deprecation-inplace>`__ 

6246 for more details. 

6247 

6248 errors : {'ignore', 'raise'}, default 'raise' 

6249 If 'ignore', suppress error and only existing labels are dropped. 

6250 

6251 Returns 

6252 ------- 

6253 Series or None 

6254 Series with specified index labels removed or None if ``inplace=True``. 

6255 

6256 Raises 

6257 ------ 

6258 KeyError 

6259 If none of the labels are found in the index. 

6260 

6261 See Also 

6262 -------- 

6263 Series.reindex : Return only specified index labels of Series. 

6264 Series.dropna : Return series without null values. 

6265 Series.drop_duplicates : Return Series with duplicate values removed. 

6266 DataFrame.drop : Drop specified labels from rows or columns. 

6267 

6268 Examples 

6269 -------- 

6270 >>> s = pd.Series(data=np.arange(3), index=["A", "B", "C"]) 

6271 >>> s 

6272 A 0 

6273 B 1 

6274 C 2 

6275 dtype: int64 

6276 

6277 Drop labels B and C 

6278 

6279 >>> s.drop(labels=["B", "C"]) 

6280 A 0 

6281 dtype: int64 

6282 

6283 Drop 2nd level label in MultiIndex Series 

6284 

6285 >>> midx = pd.MultiIndex( 

6286 ... levels=[["llama", "cow", "falcon"], ["speed", "weight", "length"]], 

6287 ... codes=[[0, 0, 0, 1, 1, 1, 2, 2, 2], [0, 1, 2, 0, 1, 2, 0, 1, 2]], 

6288 ... ) 

6289 >>> s = pd.Series([45, 200, 1.2, 30, 250, 1.5, 320, 1, 0.3], index=midx) 

6290 >>> s 

6291 llama speed 45.0 

6292 weight 200.0 

6293 length 1.2 

6294 cow speed 30.0 

6295 weight 250.0 

6296 length 1.5 

6297 falcon speed 320.0 

6298 weight 1.0 

6299 length 0.3 

6300 dtype: float64 

6301 

6302 >>> s.drop(labels="weight", level=1) 

6303 llama speed 45.0 

6304 length 1.2 

6305 cow speed 30.0 

6306 length 1.5 

6307 falcon speed 320.0 

6308 length 0.3 

6309 dtype: float64 

6310 """ 

6311 inplace = self._check_inplace_deprecation(inplace, "drop") 

6312 

6313 return super().drop( 

6314 labels=labels, 

6315 axis=axis, 

6316 index=index, 

6317 columns=columns, 

6318 level=level, 

6319 inplace=inplace, 

6320 errors=errors, 

6321 ) 

6322 

6323 def pop(self, item: Hashable) -> Any: 

6324 """ 

6325 Return item and drops from series. Raise KeyError if not found. 

6326 

6327 The Series is modified in place, and the value corresponding to the 

6328 given label is removed and returned. 

6329 

6330 Parameters 

6331 ---------- 

6332 item : label 

6333 Index of the element that needs to be removed. 

6334 

6335 Returns 

6336 ------- 

6337 scalar 

6338 Value that is popped from series. 

6339 

6340 See Also 

6341 -------- 

6342 Series.drop: Drop specified values from Series. 

6343 Series.drop_duplicates: Return Series with duplicate values removed. 

6344 

6345 Examples 

6346 -------- 

6347 >>> ser = pd.Series([1, 2, 3]) 

6348 

6349 >>> ser.pop(0) 

6350 1 

6351 

6352 >>> ser 

6353 1 2 

6354 2 3 

6355 dtype: int64 

6356 """ 

6357 return super().pop(item=item) 

6358 

6359 def info( 

6360 self, 

6361 verbose: bool | None = None, 

6362 buf: IO[str] | None = None, 

6363 max_cols: int | None = None, 

6364 memory_usage: bool | str | None = None, 

6365 show_counts: bool = True, 

6366 ) -> None: 

6367 """ 

6368 Print a concise summary of a Series. 

6369 

6370 This method prints information about a Series including 

6371 the index dtype, non-NA values and memory usage. 

6372 

6373 Parameters 

6374 ---------- 

6375 verbose : bool, optional 

6376 Whether to print the full summary. By default, the setting in 

6377 ``pandas.options.display.max_info_columns`` is followed. 

6378 buf : writable buffer, defaults to sys.stdout 

6379 Where to send the output. By default, the output is printed to 

6380 sys.stdout. Pass a writable buffer if you need to further process 

6381 the output. 

6382 max_cols : int, optional 

6383 Unused, exists only for compatibility with DataFrame.info. 

6384 memory_usage : bool, str, optional 

6385 Specifies whether total memory usage of the Series 

6386 elements (including the index) should be displayed. By default, 

6387 this follows the ``pandas.options.display.memory_usage`` setting. 

6388 

6389 True always show memory usage. False never shows memory usage. 

6390 A value of 'deep' is equivalent to "True with deep introspection". 

6391 Memory usage is shown in human-readable units (base-2 

6392 representation). Without deep introspection a memory estimation is 

6393 made based in column dtype and number of rows assuming values 

6394 consume the same memory amount for corresponding dtypes. With deep 

6395 memory introspection, a real memory usage calculation is performed 

6396 at the cost of computational resources. See the 

6397 :ref:`Frequently Asked Questions <df-memory-usage>` for more 

6398 details. 

6399 show_counts : bool, optional 

6400 Whether to show the non-null counts. By default, this is shown 

6401 only if the DataFrame is smaller than 

6402 ``pandas.options.display.max_info_rows`` and 

6403 ``pandas.options.display.max_info_columns``. A value of True always 

6404 shows the counts, and False never shows the counts. 

6405 

6406 Returns 

6407 ------- 

6408 None 

6409 This method prints a summary of a Series and returns None. 

6410 

6411 See Also 

6412 -------- 

6413 Series.describe: Generate descriptive statistics of Series. 

6414 Series.memory_usage: Memory usage of Series. 

6415 

6416 Examples 

6417 -------- 

6418 >>> int_values = [1, 2, 3, 4, 5] 

6419 >>> text_values = ["alpha", "beta", "gamma", "delta", "epsilon"] 

6420 >>> s = pd.Series(text_values, index=int_values) 

6421 >>> s.info() 

6422 <class 'pandas.Series'> 

6423 Index: 5 entries, 1 to 5 

6424 Series name: None 

6425 Non-Null Count Dtype 

6426 -------------- ----- 

6427 5 non-null str 

6428 dtypes: str(1) 

6429 memory usage: 106.0 bytes 

6430 

6431 Prints a summary excluding information about its values: 

6432 

6433 >>> s.info(verbose=False) 

6434 <class 'pandas.Series'> 

6435 Index: 5 entries, 1 to 5 

6436 dtypes: str(1) 

6437 memory usage: 106.0 bytes 

6438 

6439 Pipe output of Series.info to buffer instead of sys.stdout, get 

6440 buffer content and writes to a text file: 

6441 

6442 >>> import io 

6443 >>> buffer = io.StringIO() 

6444 >>> s.info(buf=buffer) 

6445 >>> s = buffer.getvalue() 

6446 >>> with open("df_info.txt", "w", encoding="utf-8") as f: # doctest: +SKIP 

6447 ... f.write(s) 

6448 260 

6449 

6450 The `memory_usage` parameter allows deep introspection mode, specially 

6451 useful for big Series and fine-tune memory optimization: 

6452 

6453 >>> random_strings_array = np.random.choice(["a", "b", "c"], 10**6) 

6454 >>> s = pd.Series(np.random.choice(["a", "b", "c"], 10**6)) 

6455 >>> s.info() 

6456 <class 'pandas.Series'> 

6457 RangeIndex: 1000000 entries, 0 to 999999 

6458 Series name: None 

6459 Non-Null Count Dtype 

6460 -------------- ----- 

6461 1000000 non-null str 

6462 dtypes: str(1) 

6463 memory usage: 8.6 MB 

6464 

6465 >>> s.info(memory_usage="deep") 

6466 <class 'pandas.Series'> 

6467 RangeIndex: 1000000 entries, 0 to 999999 

6468 Series name: None 

6469 Non-Null Count Dtype 

6470 -------------- ----- 

6471 1000000 non-null str 

6472 dtypes: str(1) 

6473 memory usage: 8.6 MB 

6474 """ 

6475 return SeriesInfo(self, memory_usage).render( 

6476 buf=buf, 

6477 max_cols=max_cols, 

6478 verbose=verbose, 

6479 show_counts=show_counts, 

6480 ) 

6481 

6482 def memory_usage(self, index: bool = True, deep: bool = False) -> int: 

6483 """ 

6484 Return the memory usage of the Series. 

6485 

6486 The memory usage can optionally include the contribution of 

6487 the index and of elements of `object` dtype. 

6488 

6489 Parameters 

6490 ---------- 

6491 index : bool, default True 

6492 Specifies whether to include the memory usage of the Series index. 

6493 deep : bool, default False 

6494 If True, introspect the data deeply by interrogating 

6495 `object` dtypes for system-level memory consumption, and include 

6496 it in the returned value. 

6497 

6498 Returns 

6499 ------- 

6500 int 

6501 Bytes of memory consumed. 

6502 

6503 See Also 

6504 -------- 

6505 numpy.ndarray.nbytes : Total bytes consumed by the elements of the 

6506 array. 

6507 DataFrame.memory_usage : Bytes consumed by a DataFrame. 

6508 

6509 Examples 

6510 -------- 

6511 >>> s = pd.Series(range(3)) 

6512 >>> s.memory_usage() 

6513 156 

6514 

6515 Not including the index gives the size of the rest of the data, which 

6516 is necessarily smaller: 

6517 

6518 >>> s.memory_usage(index=False) 

6519 24 

6520 

6521 The memory footprint of `object` values is ignored by default: 

6522 

6523 >>> s = pd.Series(["a", "b"]) 

6524 >>> s.values 

6525 <ArrowStringArray> 

6526 ['a', 'b'] 

6527 Length: 2, dtype: str 

6528 >>> s.memory_usage() 

6529 150 

6530 >>> s.memory_usage(deep=True) 

6531 150 

6532 """ 

6533 v = self._memory_usage(deep=deep) 

6534 if index: 

6535 v += self.index.memory_usage(deep=deep) 

6536 return v 

6537 

6538 def isin(self, values) -> Series: 

6539 """ 

6540 Whether elements in Series are contained in `values`. 

6541 

6542 Return a boolean Series showing whether each element in the Series 

6543 matches an element in the passed sequence of `values` exactly. 

6544 

6545 Parameters 

6546 ---------- 

6547 values : set or list-like 

6548 The sequence of values to test. Passing in a single string will 

6549 raise a ``TypeError``. Instead, turn a single string into a 

6550 list of one element. 

6551 

6552 Returns 

6553 ------- 

6554 Series 

6555 Series of booleans indicating if each element is in values. 

6556 

6557 Raises 

6558 ------ 

6559 TypeError 

6560 * If `values` is a string 

6561 

6562 See Also 

6563 -------- 

6564 DataFrame.isin : Equivalent method on DataFrame. 

6565 

6566 Examples 

6567 -------- 

6568 >>> s = pd.Series( 

6569 ... ["llama", "cow", "llama", "beetle", "llama", "hippo"], name="animal" 

6570 ... ) 

6571 >>> s.isin(["cow", "llama"]) 

6572 0 True 

6573 1 True 

6574 2 True 

6575 3 False 

6576 4 True 

6577 5 False 

6578 Name: animal, dtype: bool 

6579 

6580 To invert the boolean values, use the ``~`` operator: 

6581 

6582 >>> ~s.isin(["cow", "llama"]) 

6583 0 False 

6584 1 False 

6585 2 False 

6586 3 True 

6587 4 False 

6588 5 True 

6589 Name: animal, dtype: bool 

6590 

6591 Passing a single string as ``s.isin('llama')`` will raise an error. Use 

6592 a list of one element instead: 

6593 

6594 >>> s.isin(["llama"]) 

6595 0 True 

6596 1 False 

6597 2 True 

6598 3 False 

6599 4 True 

6600 5 False 

6601 Name: animal, dtype: bool 

6602 

6603 Strings and integers are distinct and are therefore not comparable: 

6604 

6605 >>> pd.Series([1]).isin(["1"]) 

6606 0 False 

6607 dtype: bool 

6608 >>> pd.Series([1.1]).isin(["1.1"]) 

6609 0 False 

6610 dtype: bool 

6611 """ 

6612 result = algorithms.isin(self._values, values) 

6613 return self._constructor(result, index=self.index, copy=False).__finalize__( 

6614 self, method="isin" 

6615 ) 

6616 

6617 def between( 

6618 self, 

6619 left, 

6620 right, 

6621 inclusive: Literal["both", "neither", "left", "right"] = "both", 

6622 ) -> Series: 

6623 """ 

6624 Return boolean Series equivalent to left <= series <= right. 

6625 

6626 This function returns a boolean vector containing `True` wherever the 

6627 corresponding Series element is between the boundary values `left` and 

6628 `right`. NA values are treated as `False`. 

6629 

6630 Parameters 

6631 ---------- 

6632 left : scalar or list-like 

6633 Left boundary. 

6634 right : scalar or list-like 

6635 Right boundary. 

6636 inclusive : {"both", "neither", "left", "right"} 

6637 Include boundaries. Whether to set each bound as closed or open. 

6638 

6639 Returns 

6640 ------- 

6641 Series 

6642 Series representing whether each element is between left and 

6643 right (inclusive). 

6644 

6645 See Also 

6646 -------- 

6647 Series.gt : Greater than of series and other. 

6648 Series.lt : Less than of series and other. 

6649 

6650 Notes 

6651 ----- 

6652 This function is equivalent to ``(left <= ser) & (ser <= right)`` 

6653 

6654 Examples 

6655 -------- 

6656 >>> s = pd.Series([2, 0, 4, 8, np.nan]) 

6657 

6658 Boundary values are included by default: 

6659 

6660 >>> s.between(1, 4) 

6661 0 True 

6662 1 False 

6663 2 True 

6664 3 False 

6665 4 False 

6666 dtype: bool 

6667 

6668 With `inclusive` set to ``"neither"`` boundary values are excluded: 

6669 

6670 >>> s.between(1, 4, inclusive="neither") 

6671 0 True 

6672 1 False 

6673 2 False 

6674 3 False 

6675 4 False 

6676 dtype: bool 

6677 

6678 `left` and `right` can be any scalar value: 

6679 

6680 >>> s = pd.Series(["Alice", "Bob", "Carol", "Eve"]) 

6681 >>> s.between("Anna", "Daniel") 

6682 0 False 

6683 1 True 

6684 2 True 

6685 3 False 

6686 dtype: bool 

6687 """ 

6688 if inclusive == "both": 

6689 lmask = self >= left 

6690 rmask = self <= right 

6691 elif inclusive == "left": 

6692 lmask = self >= left 

6693 rmask = self < right 

6694 elif inclusive == "right": 

6695 lmask = self > left 

6696 rmask = self <= right 

6697 elif inclusive == "neither": 

6698 lmask = self > left 

6699 rmask = self < right 

6700 else: 

6701 raise ValueError( 

6702 "Inclusive has to be either string of 'both'," 

6703 "'left', 'right', or 'neither'." 

6704 ) 

6705 

6706 return lmask & rmask 

6707 

6708 def case_when( 

6709 self, 

6710 caselist: list[ 

6711 tuple[ 

6712 ArrayLike | Callable[[Series], Series | np.ndarray | Sequence[bool]], 

6713 ArrayLike | Scalar | Callable[[Series], Series | np.ndarray], 

6714 ], 

6715 ], 

6716 ) -> Series: 

6717 """ 

6718 Replace values where the conditions are True. 

6719 

6720 Replacement is performed in order; for each element, the first condition 

6721 that evaluates to True determines the value used. This mirrors the semantics 

6722 of a SQL ``CASE WHEN`` expression. If no condition matches, the original 

6723 value is kept. 

6724 

6725 .. versionadded:: 2.2.0 

6726 

6727 Parameters 

6728 ---------- 

6729 caselist : A list of tuples of conditions and expected replacements 

6730 Takes the form: ``(condition0, replacement0)``, 

6731 ``(condition1, replacement1)``, ... . 

6732 ``condition`` should be a 1-D boolean array-like object 

6733 or a callable. If ``condition`` is a callable, 

6734 it is computed on the Series 

6735 and should return a boolean Series or array. 

6736 The callable must not change the input Series 

6737 (though pandas doesn`t check it). ``replacement`` should be a 

6738 1-D array-like object, a scalar or a callable. 

6739 If ``replacement`` is a callable, it is computed on the Series 

6740 and should return a scalar or Series. The callable 

6741 must not change the input Series 

6742 (though pandas doesn`t check it). 

6743 

6744 Returns 

6745 ------- 

6746 Series 

6747 A new Series with values replaced based on the provided conditions. 

6748 

6749 See Also 

6750 -------- 

6751 Series.mask : Replace values where the condition is True. 

6752 

6753 Examples 

6754 -------- 

6755 >>> c = pd.Series([6, 7, 8, 9], name="c") 

6756 >>> a = pd.Series([0, 0, 1, 2]) 

6757 >>> b = pd.Series([0, 3, 4, 5]) 

6758 

6759 >>> c.case_when( 

6760 ... caselist=[ 

6761 ... (a.gt(0), a), # condition, replacement 

6762 ... (b.gt(0), b), 

6763 ... ] 

6764 ... ) 

6765 0 6 

6766 1 3 

6767 2 1 

6768 3 2 

6769 Name: c, dtype: int64 

6770 """ 

6771 if not isinstance(caselist, list): 

6772 raise TypeError( 

6773 f"The caselist argument should be a list; instead got {type(caselist)}" 

6774 ) 

6775 

6776 if not caselist: 

6777 raise ValueError( 

6778 "provide at least one boolean condition, " 

6779 "with a corresponding replacement." 

6780 ) 

6781 

6782 for num, entry in enumerate(caselist): 

6783 if not isinstance(entry, tuple): 

6784 raise TypeError( 

6785 f"Argument {num} must be a tuple; instead got {type(entry)}." 

6786 ) 

6787 if len(entry) != 2: 

6788 raise ValueError( 

6789 f"Argument {num} must have length 2; " 

6790 "a condition and replacement; " 

6791 f"instead got length {len(entry)}." 

6792 ) 

6793 caselist = [ 

6794 ( 

6795 com.apply_if_callable(condition, self), 

6796 com.apply_if_callable(replacement, self), 

6797 ) 

6798 for condition, replacement in caselist 

6799 ] 

6800 default = self.copy(deep=False) 

6801 conditions, replacements = zip(*caselist, strict=True) 

6802 common_dtypes = [infer_dtype_from(arg)[0] for arg in [*replacements, default]] 

6803 if len(set(common_dtypes)) > 1: 

6804 common_dtype = find_common_type(common_dtypes) 

6805 updated_replacements = [] 

6806 for condition, replacement in zip(conditions, replacements, strict=True): 

6807 if is_scalar(replacement): 

6808 replacement = construct_1d_arraylike_from_scalar( 

6809 value=replacement, length=len(condition), dtype=common_dtype 

6810 ) 

6811 elif isinstance(replacement, ABCSeries): 

6812 replacement = replacement.astype(common_dtype) 

6813 else: 

6814 replacement = pd_array(replacement, dtype=common_dtype) 

6815 updated_replacements.append(replacement) 

6816 replacements = updated_replacements 

6817 default = default.astype(common_dtype) 

6818 

6819 counter = range(len(conditions) - 1, -1, -1) 

6820 for position, condition, replacement in zip( 

6821 counter, reversed(conditions), reversed(replacements), strict=True 

6822 ): 

6823 try: 

6824 default = default.mask( 

6825 condition, other=replacement, axis=0, inplace=False, level=None 

6826 ) 

6827 except Exception as error: 

6828 raise ValueError( 

6829 f"Failed to apply condition{position} and replacement{position}." 

6830 ) from error 

6831 return default 

6832 

6833 # error: Cannot determine type of 'isna' 

6834 def isna(self) -> Series: 

6835 """ 

6836 Detect missing values. 

6837 

6838 Return a boolean same-sized Series indicating if the values are NA. 

6839 NA values, such as None or :attr:`numpy.NaN`, get mapped to True 

6840 values. 

6841 Everything else gets mapped to False values. Characters such as empty 

6842 strings ``''`` or :attr:`numpy.inf` are not considered NA values. 

6843 

6844 Returns 

6845 ------- 

6846 Series 

6847 Mask of bool values for each element in Series that 

6848 indicates whether an element is an NA value. 

6849 

6850 See Also 

6851 -------- 

6852 DataFrame.isna : Detect missing values. 

6853 DataFrame.isnull : Alias of isna. 

6854 Series.notna : Boolean inverse of isna. 

6855 DataFrame.notna : Boolean inverse of isna. 

6856 Series.notnull : Alias of notna. 

6857 DataFrame.notnull : Alias of notna. 

6858 Series.dropna : Omit axes labels with missing values. 

6859 DataFrame.dropna : Omit axes labels with missing values. 

6860 isna : Top-level isna. 

6861 

6862 Examples 

6863 -------- 

6864 Show which entries in a Series are NA. 

6865 

6866 >>> ser = pd.Series([5, 6, np.nan]) 

6867 >>> ser 

6868 0 5.0 

6869 1 6.0 

6870 2 NaN 

6871 dtype: float64 

6872 >>> ser.isna() 

6873 0 False 

6874 1 False 

6875 2 True 

6876 dtype: bool 

6877 """ 

6878 return NDFrame.isna(self) 

6879 

6880 # error: Cannot determine type of 'isna' 

6881 def isnull(self) -> Series: 

6882 """ 

6883 Series.isnull is an alias for Series.isna. 

6884 

6885 Detect missing values. 

6886 

6887 Return a boolean same-sized object indicating if the values are NA. 

6888 NA values, such as None or :attr:`numpy.NaN`, gets mapped to True 

6889 values. 

6890 Everything else gets mapped to False values. Characters such as empty 

6891 strings ``''`` or :attr:`numpy.inf` are not considered NA values. 

6892 

6893 Returns 

6894 ------- 

6895 Series 

6896 Mask of bool values for each element in Series 

6897 that indicates whether an element is an NA value. 

6898 

6899 See Also 

6900 -------- 

6901 Series.isnull : Alias of isna. 

6902 DataFrame.isnull : Alias of isna. 

6903 Series.notna : Boolean inverse of isna. 

6904 DataFrame.notna : Boolean inverse of isna. 

6905 Series.dropna : Omit axes labels with missing values. 

6906 DataFrame.dropna : Omit axes labels with missing values. 

6907 isna : Top-level isna. 

6908 

6909 Examples 

6910 -------- 

6911 >>> ser = pd.Series([5, 6, np.nan]) 

6912 >>> ser 

6913 0 5.0 

6914 1 6.0 

6915 2 NaN 

6916 dtype: float64 

6917 

6918 >>> ser.isnull() 

6919 0 False 

6920 1 False 

6921 2 True 

6922 dtype: bool 

6923 """ 

6924 return super().isnull() 

6925 

6926 # error: Cannot determine type of 'notna' 

6927 def notna(self) -> Series: 

6928 """ 

6929 Detect existing (non-missing) values. 

6930 

6931 Return a boolean same-sized Series indicating if the values are not NA. 

6932 Non-missing values get mapped to True. Characters such as empty 

6933 strings ``''`` or :attr:`numpy.inf` are not considered NA values. 

6934 NA values, such as None or :attr:`numpy.NaN`, get mapped to False 

6935 values. 

6936 

6937 Returns 

6938 ------- 

6939 Series 

6940 Mask of bool values for each element in Series that 

6941 indicates whether an element is not an NA value. 

6942 

6943 See Also 

6944 -------- 

6945 Series.isna : Detect missing values. 

6946 DataFrame.isna : Detect missing values. 

6947 Series.isnull : Alias of isna. 

6948 DataFrame.isnull : Alias of isna. 

6949 DataFrame.notna : Boolean inverse of isna. 

6950 DataFrame.notnull : Alias of notna. 

6951 Series.dropna : Omit axes labels with missing values. 

6952 DataFrame.dropna : Omit axes labels with missing values. 

6953 notna : Top-level notna. 

6954 

6955 Examples 

6956 -------- 

6957 Show which entries in a Series are not NA. 

6958 

6959 >>> ser = pd.Series([5, 6, np.nan]) 

6960 >>> ser 

6961 0 5.0 

6962 1 6.0 

6963 2 NaN 

6964 dtype: float64 

6965 >>> ser.notna() 

6966 0 True 

6967 1 True 

6968 2 False 

6969 dtype: bool 

6970 """ 

6971 return super().notna() 

6972 

6973 # error: Cannot determine type of 'notna' 

6974 def notnull(self) -> Series: 

6975 """ 

6976 Series.notnull is an alias for Series.notna. 

6977 

6978 Detect existing (non-missing) values. 

6979 

6980 Return a boolean same-sized object indicating if the values are not NA. 

6981 Non-missing values get mapped to True. Characters such as empty 

6982 strings ``''`` or :attr:`numpy.inf` are not considered NA values. 

6983 NA values, such as None or :attr:`numpy.NaN`, get mapped to False 

6984 values. 

6985 

6986 Returns 

6987 ------- 

6988 Series 

6989 Mask of bool values for each element in Series 

6990 that indicates whether an element is not an NA value. 

6991 

6992 See Also 

6993 -------- 

6994 Series.notnull : Alias of notna. 

6995 DataFrame.notnull : Alias of notna. 

6996 Series.isna : Boolean inverse of notna. 

6997 DataFrame.isna : Boolean inverse of notna. 

6998 Series.dropna : Omit axes labels with missing values. 

6999 DataFrame.dropna : Omit axes labels with missing values. 

7000 notna : Top-level notna. 

7001 

7002 Examples 

7003 -------- 

7004 Show which entries in a Series are not NA. 

7005 

7006 >>> ser = pd.Series([5, 6, np.nan]) 

7007 >>> ser 

7008 0 5.0 

7009 1 6.0 

7010 2 NaN 

7011 dtype: float64 

7012 

7013 >>> ser.notnull() 

7014 0 True 

7015 1 True 

7016 2 False 

7017 dtype: bool 

7018 """ 

7019 return super().notnull() 

7020 

7021 @overload 

7022 def dropna( 

7023 self, 

7024 *, 

7025 axis: Axis = ..., 

7026 inplace: Literal[False] = ..., 

7027 how: AnyAll | None = ..., 

7028 ignore_index: bool = ..., 

7029 ) -> Series: ... 

7030 

7031 @overload 

7032 def dropna( 

7033 self, 

7034 *, 

7035 axis: Axis = ..., 

7036 inplace: Literal[True], 

7037 how: AnyAll | None = ..., 

7038 ignore_index: bool = ..., 

7039 ) -> None: ... 

7040 

7041 def dropna( 

7042 self, 

7043 *, 

7044 axis: Axis = 0, 

7045 inplace: bool | lib.NoDefault = lib.no_default, 

7046 how: AnyAll | None = None, 

7047 ignore_index: bool = False, 

7048 ) -> Series | None: 

7049 """ 

7050 Return a new Series with missing values removed. 

7051 

7052 See the :ref:`User Guide <missing_data>` for more on which values are 

7053 considered missing, and how to work with missing data. 

7054 

7055 Parameters 

7056 ---------- 

7057 axis : {0 or 'index'} 

7058 Unused. Parameter needed for compatibility with DataFrame. 

7059 inplace : bool, default False 

7060 If True, do operation inplace and return None. 

7061 

7062 .. deprecated:: 3.1.0 

7063 

7064 This keyword is deprecated and will be removed in pandas 4.0. 

7065 See the `whatsnew note on PDEP-8 

7066 <https://pandas.pydata.org/docs/dev/whatsnew/v3.1.0.html#deprecation-inplace>`__ 

7067 for more details. 

7068 

7069 how : str, optional 

7070 Not in use. Kept for compatibility. 

7071 ignore_index : bool, default ``False`` 

7072 If ``True``, the resulting axis will be labeled 0, 1, …, n - 1. 

7073 

7074 .. versionadded:: 2.0.0 

7075 

7076 Returns 

7077 ------- 

7078 Series or None 

7079 Series with NA entries dropped from it or None if ``inplace=True``. 

7080 

7081 See Also 

7082 -------- 

7083 Series.isna: Indicate missing values. 

7084 Series.notna : Indicate existing (non-missing) values. 

7085 Series.fillna : Replace missing values. 

7086 DataFrame.dropna : Drop rows or columns which contain NA values. 

7087 Index.dropna : Drop missing indices. 

7088 

7089 Examples 

7090 -------- 

7091 >>> ser = pd.Series([1.0, 2.0, np.nan]) 

7092 >>> ser 

7093 0 1.0 

7094 1 2.0 

7095 2 NaN 

7096 dtype: float64 

7097 

7098 Drop NA values from a Series. 

7099 

7100 >>> ser.dropna() 

7101 0 1.0 

7102 1 2.0 

7103 dtype: float64 

7104 

7105 Empty strings are not considered NA values. ``None`` is considered an 

7106 NA value. 

7107 

7108 >>> ser = pd.Series([np.nan, 2, pd.NaT, "", None, "I stay"]) 

7109 >>> ser 

7110 0 NaN 

7111 1 2 

7112 2 NaT 

7113 3 

7114 4 None 

7115 5 I stay 

7116 dtype: object 

7117 >>> ser.dropna() 

7118 1 2 

7119 3 

7120 5 I stay 

7121 dtype: object 

7122 """ 

7123 inplace = self._check_inplace_deprecation(inplace, "dropna") 

7124 inplace = validate_bool_kwarg(inplace, "inplace") 

7125 ignore_index = validate_bool_kwarg(ignore_index, "ignore_index") 

7126 # Validate the axis parameter 

7127 self._get_axis_number(axis or 0) 

7128 

7129 if self._can_hold_na: 

7130 result = remove_na_arraylike(self) 

7131 elif not inplace: 

7132 result = self.copy(deep=False) 

7133 else: 

7134 result = self 

7135 

7136 if ignore_index: 

7137 result.index = default_index(len(result)) 

7138 

7139 if inplace: 

7140 return self._update_inplace(result) 

7141 else: 

7142 return result 

7143 

7144 # ---------------------------------------------------------------------- 

7145 # Time series-oriented methods 

7146 

7147 def to_timestamp( 

7148 self, 

7149 freq: Frequency | None = None, 

7150 how: ToTimestampHow = "start", 

7151 copy: bool | lib.NoDefault = lib.no_default, 

7152 ) -> Series: 

7153 """ 

7154 Cast to DatetimeIndex of Timestamps, at *beginning* of period. 

7155 

7156 This can be changed to the *end* of the period, by specifying `how="e"`. 

7157 

7158 Parameters 

7159 ---------- 

7160 freq : str, default frequency of PeriodIndex 

7161 Desired frequency. 

7162 how : {'start', 'end', 's', 'e'}, default 'start' 

7163 Convention for converting period to timestamp; start of period 

7164 vs. end. Case-insensitive. 

7165 copy : bool, default False 

7166 This keyword is now ignored; changing its value will have no 

7167 impact on the method. 

7168 

7169 .. deprecated:: 3.0.0 

7170 

7171 This keyword is ignored and will be removed in pandas 4.0. Since 

7172 pandas 3.0, this method always returns a new object using a lazy 

7173 copy mechanism that defers copies until necessary 

7174 (Copy-on-Write). See the `user guide on Copy-on-Write 

7175 <https://pandas.pydata.org/docs/dev/user_guide/migration.html>`__ 

7176 for more details. 

7177 

7178 Returns 

7179 ------- 

7180 Series with DatetimeIndex 

7181 Series with the PeriodIndex cast to DatetimeIndex. 

7182 

7183 See Also 

7184 -------- 

7185 Series.to_period: Inverse method to cast DatetimeIndex to PeriodIndex. 

7186 DataFrame.to_timestamp: Equivalent method for DataFrame. 

7187 

7188 Examples 

7189 -------- 

7190 >>> idx = pd.PeriodIndex(["2023", "2024", "2025"], freq="Y") 

7191 >>> s1 = pd.Series([1, 2, 3], index=idx) 

7192 >>> s1 

7193 2023 1 

7194 2024 2 

7195 2025 3 

7196 Freq: Y-DEC, dtype: int64 

7197 

7198 The resulting frequency of the Timestamps is `YearBegin` 

7199 

7200 >>> s1 = s1.to_timestamp() 

7201 >>> s1 

7202 2023-01-01 1 

7203 2024-01-01 2 

7204 2025-01-01 3 

7205 Freq: YS-JAN, dtype: int64 

7206 

7207 Using `freq` which is the offset that the Timestamps will have 

7208 

7209 >>> s2 = pd.Series([1, 2, 3], index=idx) 

7210 >>> s2 = s2.to_timestamp(freq="M") 

7211 >>> s2 

7212 2023-01-31 1 

7213 2024-01-31 2 

7214 2025-01-31 3 

7215 Freq: YE-JAN, dtype: int64 

7216 """ 

7217 self._check_copy_deprecation(copy) 

7218 if not isinstance(self.index, PeriodIndex): 

7219 raise TypeError(f"unsupported Type {type(self.index).__name__}") 

7220 

7221 new_obj = self.copy(deep=False) 

7222 new_index = self.index.to_timestamp(freq=freq, how=how) 

7223 setattr(new_obj, "index", new_index) 

7224 return new_obj 

7225 

7226 def to_period( 

7227 self, 

7228 freq: str | None = None, 

7229 copy: bool | lib.NoDefault = lib.no_default, 

7230 ) -> Series: 

7231 """ 

7232 Convert Series from DatetimeIndex to PeriodIndex. 

7233 

7234 This method converts the DatetimeIndex of the Series into a 

7235 PeriodIndex with a specified frequency, which is useful when 

7236 period-based indexing is preferred over exact timestamps. 

7237 

7238 Parameters 

7239 ---------- 

7240 freq : str, default None 

7241 Frequency associated with the PeriodIndex. 

7242 copy : bool, default False 

7243 This keyword is now ignored; changing its value will have no 

7244 impact on the method. 

7245 

7246 .. deprecated:: 3.0.0 

7247 

7248 This keyword is ignored and will be removed in pandas 4.0. Since 

7249 pandas 3.0, this method always returns a new object using a lazy 

7250 copy mechanism that defers copies until necessary 

7251 (Copy-on-Write). See the `user guide on Copy-on-Write 

7252 <https://pandas.pydata.org/docs/dev/user_guide/migration.html>`__ 

7253 for more details. 

7254 

7255 Returns 

7256 ------- 

7257 Series 

7258 Series with index converted to PeriodIndex. 

7259 

7260 See Also 

7261 -------- 

7262 DataFrame.to_period: Equivalent method for DataFrame. 

7263 Series.dt.to_period: Convert DateTime column values. 

7264 

7265 Examples 

7266 -------- 

7267 >>> idx = pd.DatetimeIndex(["2023", "2024", "2025"]) 

7268 >>> s = pd.Series([1, 2, 3], index=idx) 

7269 >>> s = s.to_period() 

7270 >>> s 

7271 2023 1 

7272 2024 2 

7273 2025 3 

7274 Freq: Y-DEC, dtype: int64 

7275 

7276 Viewing the index 

7277 

7278 >>> s.index 

7279 PeriodIndex(['2023', '2024', '2025'], dtype='period[Y-DEC]') 

7280 """ 

7281 self._check_copy_deprecation(copy) 

7282 if not isinstance(self.index, DatetimeIndex): 

7283 raise TypeError(f"unsupported Type {type(self.index).__name__}") 

7284 

7285 new_obj = self.copy(deep=False) 

7286 new_index = self.index.to_period(freq=freq) 

7287 setattr(new_obj, "index", new_index) 

7288 return new_obj 

7289 

7290 # ---------------------------------------------------------------------- 

7291 # Add index 

7292 _AXIS_ORDERS: list[Literal["index", "columns"]] = ["index"] 

7293 _AXIS_LEN = len(_AXIS_ORDERS) 

7294 _info_axis_number: Literal[0] = 0 

7295 _info_axis_name: Literal["index"] = "index" 

7296 

7297 index = properties.AxisProperty( 

7298 axis=0, 

7299 doc=""" 

7300 The index (axis labels) of the Series. 

7301 

7302 The index of a Series is used to label and identify each element of the 

7303 underlying data. The index can be thought of as an immutable ordered set 

7304 (technically a multi-set, as it may contain duplicate labels), and is 

7305 used to index and align data in pandas. 

7306 

7307 Returns 

7308 ------- 

7309 Index 

7310 The index labels of the Series. 

7311 

7312 See Also 

7313 -------- 

7314 Series.reindex : Conform Series to new index. 

7315 Index : The base pandas index type. 

7316 

7317 Notes 

7318 ----- 

7319 For more information on pandas indexing, see the `indexing user guide 

7320 <https://pandas.pydata.org/docs/user_guide/indexing.html>`__. 

7321 

7322 Examples 

7323 -------- 

7324 To create a Series with a custom index and view the index labels: 

7325 

7326 >>> cities = ['Kolkata', 'Chicago', 'Toronto', 'Lisbon'] 

7327 >>> populations = [14.85, 2.71, 2.93, 0.51] 

7328 >>> city_series = pd.Series(populations, index=cities) 

7329 >>> city_series.index 

7330 Index(['Kolkata', 'Chicago', 'Toronto', 'Lisbon'], dtype='object') 

7331 

7332 To change the index labels of an existing Series: 

7333 

7334 >>> city_series.index = ['KOL', 'CHI', 'TOR', 'LIS'] 

7335 >>> city_series.index 

7336 Index(['KOL', 'CHI', 'TOR', 'LIS'], dtype='object') 

7337 """, 

7338 ) 

7339 

7340 # ---------------------------------------------------------------------- 

7341 # Accessor Methods 

7342 # ---------------------------------------------------------------------- 

7343 str = Accessor("str", StringMethods) 

7344 dt = Accessor("dt", CombinedDatetimelikeProperties) 

7345 cat = Accessor("cat", CategoricalAccessor) 

7346 plot = Accessor("plot", pandas.plotting.PlotAccessor) 

7347 sparse = Accessor("sparse", SparseAccessor) 

7348 struct = Accessor("struct", StructAccessor) 

7349 list = Accessor("list", ListAccessor) 

7350 

7351 # ---------------------------------------------------------------------- 

7352 # Add plotting methods to Series 

7353 hist = pandas.plotting.hist_series 

7354 

7355 # ---------------------------------------------------------------------- 

7356 # Template-Based Arithmetic/Comparison Methods 

7357 

7358 def _cmp_method(self, other, op) -> Series: 

7359 res_name = ops.get_op_result_name(self, other) 

7360 

7361 if isinstance(other, Series) and not self._indexed_same(other): 

7362 raise ValueError("Can only compare identically-labeled Series objects") 

7363 

7364 lvalues = self._values 

7365 if not isinstance(lvalues, ExtensionArray) and lvalues.dtype != object: 

7366 # For EA-backed values the warning is emitted by the EA's own 

7367 # _cmp_method; object dtype already treats a non-standard listlike 

7368 # as scalar-like, so it needs no warning either (GH#62423). 

7369 ops.maybe_warn_listlike(other) 

7370 rvalues = extract_array(other, extract_numpy=True, extract_range=True) 

7371 

7372 res_values = ops.comparison_op(lvalues, rvalues, op) 

7373 

7374 return self._construct_result(res_values, name=res_name, other=other) 

7375 

7376 def _logical_method(self, other, op) -> Series: 

7377 res_name = ops.get_op_result_name(self, other) 

7378 self, other = self._align_for_op(other, align_asobject=True) 

7379 

7380 lvalues = self._values 

7381 rvalues = extract_array(other, extract_numpy=True, extract_range=True) 

7382 

7383 res_values = ops.logical_op(lvalues, rvalues, op) 

7384 return self._construct_result(res_values, name=res_name, other=other) 

7385 

7386 def _arith_method(self, other, op) -> Series: 

7387 self, other = self._align_for_op(other) 

7388 return base.IndexOpsMixin._arith_method(self, other, op) 

7389 

7390 def _align_for_op(self, right, align_asobject: bool = False): 

7391 """align lhs and rhs Series""" 

7392 # TODO: Different from DataFrame._align_for_op, list, tuple and ndarray 

7393 # are not coerced here 

7394 # because Series has inconsistencies described in GH#13637 

7395 left = self 

7396 

7397 if isinstance(right, Series): 

7398 # avoid repeated alignment 

7399 if not left.index.equals(right.index): 

7400 if align_asobject: 

7401 if left.dtype not in (object, np.bool_) or right.dtype not in ( 

7402 object, 

7403 np.bool_, 

7404 ): 

7405 pass 

7406 # GH#52538 no longer cast in these cases 

7407 else: 

7408 # to keep original value's dtype for bool ops 

7409 left = left.astype(object) 

7410 right = right.astype(object) 

7411 

7412 left, right = left.align(right) 

7413 

7414 return left, right 

7415 

7416 def _binop(self, other: Series, func, level=None, fill_value=None) -> Series: 

7417 """ 

7418 Perform generic binary operation with optional fill value. 

7419 

7420 Parameters 

7421 ---------- 

7422 other : Series 

7423 func : binary operator 

7424 fill_value : float or object 

7425 Value to substitute for NA/null values. If both Series are NA in a 

7426 location, the result will be NA regardless of the passed fill value. 

7427 level : int or level name, default None 

7428 Broadcast across a level, matching Index values on the 

7429 passed MultiIndex level. 

7430 

7431 Returns 

7432 ------- 

7433 Series 

7434 """ 

7435 this = self 

7436 

7437 if not self.index.equals(other.index): 

7438 this, other = self.align(other, level=level, join="outer") 

7439 

7440 this_vals, other_vals = ops.fill_binop(this._values, other._values, fill_value) 

7441 

7442 with np.errstate(all="ignore"): 

7443 result = func(this_vals, other_vals) 

7444 

7445 name = ops.get_op_result_name(self, other) 

7446 

7447 out = this._construct_result(result, name, other) 

7448 return cast("Series", out) 

7449 

7450 @overload 

7451 def _construct_result( 

7452 self, 

7453 result: ArrayLike, 

7454 name: Hashable, 

7455 other: AnyArrayLike | DataFrame, 

7456 ) -> Series: ... 

7457 

7458 @overload 

7459 def _construct_result( 

7460 self, 

7461 result: tuple[ArrayLike, ArrayLike], 

7462 name: Hashable, 

7463 other: AnyArrayLike | DataFrame, 

7464 ) -> tuple[Series, Series]: ... 

7465 

7466 def _construct_result( 

7467 self, 

7468 result: ArrayLike | tuple[ArrayLike, ArrayLike], 

7469 name: Hashable, 

7470 other: AnyArrayLike | DataFrame, 

7471 ) -> Series | tuple[Series, Series]: 

7472 """ 

7473 Construct an appropriately-labelled Series from the result of an op. 

7474 

7475 Parameters 

7476 ---------- 

7477 result : ndarray or ExtensionArray 

7478 name : Label 

7479 other : Series, DataFrame or array-like 

7480 

7481 Returns 

7482 ------- 

7483 Series 

7484 In the case of __divmod__ or __rdivmod__, a 2-tuple of Series. 

7485 """ 

7486 if isinstance(result, tuple): 

7487 # produced by divmod or rdivmod 

7488 

7489 res1 = self._construct_result(result[0], name=name, other=other) 

7490 res2 = self._construct_result(result[1], name=name, other=other) 

7491 

7492 # GH#33427 assertions to keep mypy happy 

7493 assert isinstance(res1, Series) 

7494 assert isinstance(res2, Series) 

7495 return (res1, res2) 

7496 

7497 # TODO: result should always be ArrayLike, but this fails for some 

7498 # JSONArray tests 

7499 dtype = getattr(result, "dtype", None) 

7500 out = self._constructor(result, index=self.index, dtype=dtype, copy=False) 

7501 out = out.__finalize__(self) 

7502 out = out.__finalize__(other) 

7503 

7504 # Set the result's name after __finalize__ is called because __finalize__ 

7505 # would set it back to self.name 

7506 out.name = name 

7507 return out 

7508 

7509 def _flex_method( 

7510 self, other, op, *, level=None, fill_value=None, axis: Axis = 0 

7511 ) -> Series: 

7512 if axis is not None: 

7513 self._get_axis_number(axis) 

7514 

7515 res_name = ops.get_op_result_name(self, other) 

7516 

7517 if isinstance(other, Series): 

7518 return self._binop(other, op, level=level, fill_value=fill_value) 

7519 elif (isinstance(other, np.ndarray) and other.ndim > 0) or isinstance( 

7520 other, (list, tuple, ExtensionArray) 

7521 ): 

7522 if isinstance(other, tuple): 

7523 op_name = op.__name__.strip("_") 

7524 warnings.warn( 

7525 f"Series.{op_name} with a tuple is deprecated and will be " 

7526 "treated as scalar-like in a future version. " 

7527 "Explicitly wrap in a numpy array instead.", 

7528 Pandas4Warning, 

7529 stacklevel=find_stack_level(), 

7530 ) 

7531 if len(other) != len(self): 

7532 raise ValueError("Lengths must be equal") 

7533 other = self._constructor(other, self.index, copy=False) 

7534 result = self._binop(other, op, level=level, fill_value=fill_value) 

7535 result._name = res_name 

7536 return result 

7537 elif isinstance(other, ABCDataFrame): 

7538 # GH#46179 

7539 raise TypeError( 

7540 f"Series.{op.__name__.strip('_')} does not support a DataFrame " 

7541 f"`other`. Use df.{op.__name__.strip('_')}(ser) instead." 

7542 ) 

7543 else: 

7544 if fill_value is not None: 

7545 if isna(other): 

7546 return op(self, fill_value) 

7547 self = self.fillna(fill_value) 

7548 

7549 return op(self, other) 

7550 

7551 def eq( 

7552 self, 

7553 other, 

7554 level: Level | None = None, 

7555 fill_value: float | None = None, 

7556 axis: Axis = 0, 

7557 ) -> Series: 

7558 """ 

7559 Return Equal to of series and other, element-wise (binary operator `eq`). 

7560 

7561 Equivalent to ``series == other``, but with support to substitute a 

7562 fill_value for missing data in either one of the inputs. 

7563 

7564 Parameters 

7565 ---------- 

7566 other : object 

7567 When a Series is provided, will align on indexes. For all other types, 

7568 will behave the same as ``==`` but with possibly different results due 

7569 to the other arguments. 

7570 level : int or name 

7571 Broadcast across a level, matching Index values on the 

7572 passed MultiIndex level. 

7573 fill_value : scalar or None, default None 

7574 Fill NA values, whether present in the original data or introduced 

7575 by alignment, with this value before computation. Positions where 

7576 both inputs are NA are left unfilled and behave as NA does for the 

7577 operation. 

7578 axis : {0 or 'index'} 

7579 Unused. Parameter needed for compatibility with DataFrame. 

7580 

7581 Returns 

7582 ------- 

7583 Series 

7584 The result of the operation. 

7585 

7586 See Also 

7587 -------- 

7588 Series.ge : Return elementwise Greater than or equal to of series and other. 

7589 Series.le : Return elementwise Less than or equal to of series and other. 

7590 Series.gt : Return elementwise Greater than of series and other. 

7591 Series.lt : Return elementwise Less than of series and other. 

7592 

7593 Examples 

7594 -------- 

7595 >>> a = pd.Series([1, 1, 1, np.nan], index=["a", "b", "c", "d"]) 

7596 >>> a 

7597 a 1.0 

7598 b 1.0 

7599 c 1.0 

7600 d NaN 

7601 dtype: float64 

7602 >>> b = pd.Series([1, np.nan, 1, np.nan], index=["a", "b", "d", "e"]) 

7603 >>> b 

7604 a 1.0 

7605 b NaN 

7606 d 1.0 

7607 e NaN 

7608 dtype: float64 

7609 >>> a.eq(b, fill_value=0) 

7610 a True 

7611 b False 

7612 c False 

7613 d False 

7614 e False 

7615 dtype: bool 

7616 """ 

7617 return self._flex_method( 

7618 other, operator.eq, level=level, fill_value=fill_value, axis=axis 

7619 ) 

7620 

7621 def ne(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series: 

7622 """ 

7623 Return Not equal to of series and other, element-wise (binary operator `ne`). 

7624 

7625 Equivalent to ``series != other``, but with support to substitute a 

7626 fill_value for missing data in either one of the inputs. 

7627 

7628 Parameters 

7629 ---------- 

7630 other : object 

7631 When a Series is provided, will align on indexes. For all other types, 

7632 will behave the same as ``!=`` but with possibly different results due 

7633 to the other arguments. 

7634 level : int or name 

7635 Broadcast across a level, matching Index values on the 

7636 passed MultiIndex level. 

7637 fill_value : scalar or None, default None 

7638 Fill NA values, whether present in the original data or introduced 

7639 by alignment, with this value before computation. Positions where 

7640 both inputs are NA are left unfilled and behave as NA does for the 

7641 operation. 

7642 axis : {0 or 'index'} 

7643 Unused. Parameter needed for compatibility with DataFrame. 

7644 

7645 Returns 

7646 ------- 

7647 Series 

7648 The result of the operation. 

7649 

7650 See Also 

7651 -------- 

7652 Series.eq : Reverse of the Not equal to operator, see 

7653 `Python documentation 

7654 <https://docs.python.org/3/reference/datamodel.html#emulating-numeric-types>`_ 

7655 for more details. 

7656 

7657 Examples 

7658 -------- 

7659 >>> a = pd.Series([1, 1, 1, np.nan], index=["a", "b", "c", "d"]) 

7660 >>> a 

7661 a 1.0 

7662 b 1.0 

7663 c 1.0 

7664 d NaN 

7665 dtype: float64 

7666 >>> b = pd.Series([1, np.nan, 1, np.nan], index=["a", "b", "d", "e"]) 

7667 >>> b 

7668 a 1.0 

7669 b NaN 

7670 d 1.0 

7671 e NaN 

7672 dtype: float64 

7673 >>> a.ne(b, fill_value=0) 

7674 a False 

7675 b True 

7676 c True 

7677 d True 

7678 e True 

7679 dtype: bool 

7680 """ 

7681 return self._flex_method( 

7682 other, operator.ne, level=level, fill_value=fill_value, axis=axis 

7683 ) 

7684 

7685 def le(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series: 

7686 """ 

7687 Return Less than or equal to of series and other, \ 

7688 element-wise (binary operator `le`). 

7689 

7690 Equivalent to ``series <= other``, but with support to substitute a 

7691 fill_value for missing data in either one of the inputs. 

7692 

7693 Parameters 

7694 ---------- 

7695 other : object 

7696 When a Series is provided, will align on indexes. For all other types, 

7697 will behave the same as ``<=`` but with possibly different results due 

7698 to the other arguments. 

7699 level : int or name 

7700 Broadcast across a level, matching Index values on the 

7701 passed MultiIndex level. 

7702 fill_value : scalar or None, default None 

7703 Fill NA values, whether present in the original data or introduced 

7704 by alignment, with this value before computation. Positions where 

7705 both inputs are NA are left unfilled and behave as NA does for the 

7706 operation. 

7707 axis : {0 or 'index'} 

7708 Unused. Parameter needed for compatibility with DataFrame. 

7709 

7710 Returns 

7711 ------- 

7712 Series 

7713 The result of the operation. 

7714 

7715 See Also 

7716 -------- 

7717 Series.ge : Return elementwise Greater than or equal to of series and other. 

7718 Series.lt : Return elementwise Less than of series and other. 

7719 Series.gt : Return elementwise Greater than of series and other. 

7720 Series.eq : Return elementwise equal to of series and other. 

7721 

7722 Examples 

7723 -------- 

7724 >>> a = pd.Series([1, 1, 1, np.nan, 1], index=['a', 'b', 'c', 'd', 'e']) 

7725 >>> a 

7726 a 1.0 

7727 b 1.0 

7728 c 1.0 

7729 d NaN 

7730 e 1.0 

7731 dtype: float64 

7732 >>> b = pd.Series([0, 1, 2, np.nan, 1], index=['a', 'b', 'c', 'd', 'f']) 

7733 >>> b 

7734 a 0.0 

7735 b 1.0 

7736 c 2.0 

7737 d NaN 

7738 f 1.0 

7739 dtype: float64 

7740 >>> a.le(b, fill_value=0) 

7741 a False 

7742 b True 

7743 c True 

7744 d False 

7745 e False 

7746 f True 

7747 dtype: bool 

7748 """ 

7749 return self._flex_method( 

7750 other, operator.le, level=level, fill_value=fill_value, axis=axis 

7751 ) 

7752 

7753 def lt(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series: 

7754 """ 

7755 Return Less than of series and other, element-wise (binary operator `lt`). 

7756 

7757 Equivalent to ``series < other``, but with support to substitute a 

7758 fill_value for missing data in either one of the inputs. 

7759 

7760 Parameters 

7761 ---------- 

7762 other : object 

7763 When a Series is provided, will align on indexes. For all other types, 

7764 will behave the same as ``<`` but with possibly different results due 

7765 to the other arguments. 

7766 level : int or name 

7767 Broadcast across a level, matching Index values on the 

7768 passed MultiIndex level. 

7769 fill_value : scalar or None, default None 

7770 Fill NA values, whether present in the original data or introduced 

7771 by alignment, with this value before computation. Positions where 

7772 both inputs are NA are left unfilled and behave as NA does for the 

7773 operation. 

7774 axis : {0 or 'index'} 

7775 Unused. Parameter needed for compatibility with DataFrame. 

7776 

7777 Returns 

7778 ------- 

7779 Series 

7780 The result of the operation. 

7781 

7782 See Also 

7783 -------- 

7784 Series.gt : Element-wise Greater than, see 

7785 `Python documentation 

7786 <https://docs.python.org/3/reference/datamodel.html#emulating-numeric-types>`_ 

7787 for more details. 

7788 

7789 Examples 

7790 -------- 

7791 >>> a = pd.Series([1, 1, 1, np.nan, 1], index=["a", "b", "c", "d", "e"]) 

7792 >>> a 

7793 a 1.0 

7794 b 1.0 

7795 c 1.0 

7796 d NaN 

7797 e 1.0 

7798 dtype: float64 

7799 >>> b = pd.Series([0, 1, 2, np.nan, 1], index=["a", "b", "c", "d", "f"]) 

7800 >>> b 

7801 a 0.0 

7802 b 1.0 

7803 c 2.0 

7804 d NaN 

7805 f 1.0 

7806 dtype: float64 

7807 >>> a.lt(b, fill_value=0) 

7808 a False 

7809 b False 

7810 c True 

7811 d False 

7812 e False 

7813 f True 

7814 dtype: bool 

7815 """ 

7816 return self._flex_method( 

7817 other, operator.lt, level=level, fill_value=fill_value, axis=axis 

7818 ) 

7819 

7820 def ge(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series: 

7821 """ 

7822 Return Greater than or equal to of series and other, \ 

7823 element-wise (binary operator `ge`). 

7824 

7825 Equivalent to ``series >= other``, but with support to substitute a 

7826 fill_value for missing data in either one of the inputs. 

7827 

7828 Parameters 

7829 ---------- 

7830 other : object 

7831 When a Series is provided, will align on indexes. For all other types, 

7832 will behave the same as ``>=`` but with possibly different results due 

7833 to the other arguments. 

7834 level : int or name 

7835 Broadcast across a level, matching Index values on the 

7836 passed MultiIndex level. 

7837 fill_value : scalar or None, default None 

7838 Fill NA values, whether present in the original data or introduced 

7839 by alignment, with this value before computation. Positions where 

7840 both inputs are NA are left unfilled and behave as NA does for the 

7841 operation. 

7842 axis : {0 or 'index'} 

7843 Unused. Parameter needed for compatibility with DataFrame. 

7844 

7845 Returns 

7846 ------- 

7847 Series 

7848 The result of the operation. 

7849 

7850 See Also 

7851 -------- 

7852 Series.gt : Greater than comparison, element-wise. 

7853 Series.le : Less than or equal to comparison, element-wise. 

7854 Series.lt : Less than comparison, element-wise. 

7855 Series.eq : Equal to comparison, element-wise. 

7856 Series.ne : Not equal to comparison, element-wise. 

7857 

7858 Examples 

7859 -------- 

7860 >>> a = pd.Series([1, 1, 1, np.nan, 1], index=["a", "b", "c", "d", "e"]) 

7861 >>> a 

7862 a 1.0 

7863 b 1.0 

7864 c 1.0 

7865 d NaN 

7866 e 1.0 

7867 dtype: float64 

7868 >>> b = pd.Series([0, 1, 2, np.nan, 1], index=["a", "b", "c", "d", "f"]) 

7869 >>> b 

7870 a 0.0 

7871 b 1.0 

7872 c 2.0 

7873 d NaN 

7874 f 1.0 

7875 dtype: float64 

7876 >>> a.ge(b, fill_value=0) 

7877 a True 

7878 b True 

7879 c False 

7880 d False 

7881 e True 

7882 f False 

7883 dtype: bool 

7884 """ 

7885 return self._flex_method( 

7886 other, operator.ge, level=level, fill_value=fill_value, axis=axis 

7887 ) 

7888 

7889 def gt(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series: 

7890 """ 

7891 Return Greater than of series and other, element-wise (binary operator `gt`). 

7892 

7893 Equivalent to ``series > other``, but with support to substitute a 

7894 fill_value for missing data in either one of the inputs. 

7895 

7896 Parameters 

7897 ---------- 

7898 other : object 

7899 When a Series is provided, will align on indexes. For all other types, 

7900 will behave the same as ``>`` but with possibly different results due 

7901 to the other arguments. 

7902 level : int or name 

7903 Broadcast across a level, matching Index values on the 

7904 passed MultiIndex level. 

7905 fill_value : scalar or None, default None 

7906 Fill NA values, whether present in the original data or introduced 

7907 by alignment, with this value before computation. Positions where 

7908 both inputs are NA are left unfilled and behave as NA does for the 

7909 operation. 

7910 axis : {0 or 'index'} 

7911 Unused. Parameter needed for compatibility with DataFrame. 

7912 

7913 Returns 

7914 ------- 

7915 Series 

7916 The result of the operation. 

7917 

7918 See Also 

7919 -------- 

7920 Series.lt : Reverse of the Greater than operator, see 

7921 `Python documentation 

7922 <https://docs.python.org/3/reference/datamodel.html#emulating-numeric-types>`_ 

7923 for more details. 

7924 

7925 Examples 

7926 -------- 

7927 >>> a = pd.Series([1, 1, 1, np.nan, 1], index=["a", "b", "c", "d", "e"]) 

7928 >>> a 

7929 a 1.0 

7930 b 1.0 

7931 c 1.0 

7932 d NaN 

7933 e 1.0 

7934 dtype: float64 

7935 >>> b = pd.Series([0, 1, 2, np.nan, 1], index=["a", "b", "c", "d", "f"]) 

7936 >>> b 

7937 a 0.0 

7938 b 1.0 

7939 c 2.0 

7940 d NaN 

7941 f 1.0 

7942 dtype: float64 

7943 >>> a.gt(b, fill_value=0) 

7944 a True 

7945 b False 

7946 c False 

7947 d False 

7948 e True 

7949 f False 

7950 dtype: bool 

7951 """ 

7952 return self._flex_method( 

7953 other, operator.gt, level=level, fill_value=fill_value, axis=axis 

7954 ) 

7955 

7956 def add(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series: 

7957 """ 

7958 Return Addition of series and other, element-wise (binary operator `add`). 

7959 

7960 Equivalent to ``series + other``, but with support to substitute a 

7961 fill_value for missing data in either one of the inputs. 

7962 

7963 Parameters 

7964 ---------- 

7965 other : Series or scalar value 

7966 With which to compute the addition. 

7967 level : int or name 

7968 Broadcast across a level, matching Index values on the 

7969 passed MultiIndex level. 

7970 fill_value : scalar or None, default None 

7971 Fill NA values, whether present in the original data or introduced 

7972 by alignment, with this value before computation. Positions where 

7973 both inputs are NA are left unfilled and behave as NA does for the 

7974 operation. 

7975 axis : {0 or 'index'} 

7976 Unused. Parameter needed for compatibility with DataFrame. 

7977 

7978 Returns 

7979 ------- 

7980 Series 

7981 The result of the operation. 

7982 

7983 See Also 

7984 -------- 

7985 Series.radd : Reverse of the Addition operator, see 

7986 `Python documentation 

7987 <https://docs.python.org/3/reference/datamodel.html#emulating-numeric-types>`_ 

7988 for more details. 

7989 

7990 Examples 

7991 -------- 

7992 >>> a = pd.Series([1, 1, 1, np.nan], index=["a", "b", "c", "d"]) 

7993 >>> a 

7994 a 1.0 

7995 b 1.0 

7996 c 1.0 

7997 d NaN 

7998 dtype: float64 

7999 >>> b = pd.Series([1, np.nan, 1, np.nan], index=["a", "b", "d", "e"]) 

8000 >>> b 

8001 a 1.0 

8002 b NaN 

8003 d 1.0 

8004 e NaN 

8005 dtype: float64 

8006 >>> a.add(b, fill_value=0) 

8007 a 2.0 

8008 b 1.0 

8009 c 1.0 

8010 d 1.0 

8011 e NaN 

8012 dtype: float64 

8013 """ 

8014 return self._flex_method( 

8015 other, operator.add, level=level, fill_value=fill_value, axis=axis 

8016 ) 

8017 

8018 def radd(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series: 

8019 """ 

8020 Return Addition of series and other, element-wise (binary operator `radd`). 

8021 

8022 Equivalent to ``other + series``, but with support to substitute a 

8023 fill_value for missing data in either one of the inputs. 

8024 

8025 Parameters 

8026 ---------- 

8027 other : object 

8028 When a Series is provided, will align on indexes. For all other types, 

8029 will behave the same as ``+`` but with possibly different results due 

8030 to the other arguments. 

8031 level : int or name 

8032 Broadcast across a level, matching Index values on the 

8033 passed MultiIndex level. 

8034 fill_value : scalar or None, default None 

8035 Fill NA values, whether present in the original data or introduced 

8036 by alignment, with this value before computation. Positions where 

8037 both inputs are NA are left unfilled and behave as NA does for the 

8038 operation. 

8039 axis : {0 or 'index'} 

8040 Unused. Parameter needed for compatibility with DataFrame. 

8041 

8042 Returns 

8043 ------- 

8044 Series 

8045 The result of the operation. 

8046 

8047 See Also 

8048 -------- 

8049 Series.add : Element-wise Addition, see 

8050 `Python documentation 

8051 <https://docs.python.org/3/reference/datamodel.html#emulating-numeric-types>`_ 

8052 for more details. 

8053 

8054 Examples 

8055 -------- 

8056 >>> a = pd.Series([1, 1, 1, np.nan], index=["a", "b", "c", "d"]) 

8057 >>> a 

8058 a 1.0 

8059 b 1.0 

8060 c 1.0 

8061 d NaN 

8062 dtype: float64 

8063 >>> b = pd.Series([1, np.nan, 1, np.nan], index=["a", "b", "d", "e"]) 

8064 >>> b 

8065 a 1.0 

8066 b NaN 

8067 d 1.0 

8068 e NaN 

8069 dtype: float64 

8070 >>> a.radd(b, fill_value=1.0) 

8071 a 2.0 

8072 b 2.0 

8073 c 2.0 

8074 d 2.0 

8075 e NaN 

8076 dtype: float64 

8077 """ 

8078 return self._flex_method( 

8079 other, roperator.radd, level=level, fill_value=fill_value, axis=axis 

8080 ) 

8081 

8082 def sub(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series: 

8083 """ 

8084 Return Subtraction of series and other, element-wise (binary operator `sub`). 

8085 

8086 Equivalent to ``series - other``, but with support to substitute a 

8087 fill_value for missing data in either one of the inputs. 

8088 

8089 Parameters 

8090 ---------- 

8091 other : object 

8092 When a Series is provided, will align on indexes. For all other types, 

8093 will behave the same as ``-`` but with possibly different results due 

8094 to the other arguments. 

8095 level : int or name 

8096 Broadcast across a level, matching Index values on the 

8097 passed MultiIndex level. 

8098 fill_value : scalar or None, default None 

8099 Fill NA values, whether present in the original data or introduced 

8100 by alignment, with this value before computation. Positions where 

8101 both inputs are NA are left unfilled and behave as NA does for the 

8102 operation. 

8103 axis : {0 or 'index'} 

8104 Unused. Parameter needed for compatibility with DataFrame. 

8105 

8106 Returns 

8107 ------- 

8108 Series 

8109 The result of the operation. 

8110 

8111 See Also 

8112 -------- 

8113 Series.rsub : Reverse of the Subtraction operator, see 

8114 `Python documentation 

8115 <https://docs.python.org/3/reference/datamodel.html#emulating-numeric-types>`_ 

8116 for more details. 

8117 

8118 Examples 

8119 -------- 

8120 >>> a = pd.Series([1, 1, 1, np.nan], index=["a", "b", "c", "d"]) 

8121 >>> a 

8122 a 1.0 

8123 b 1.0 

8124 c 1.0 

8125 d NaN 

8126 dtype: float64 

8127 >>> b = pd.Series([1, np.nan, 1, np.nan], index=["a", "b", "d", "e"]) 

8128 >>> b 

8129 a 1.0 

8130 b NaN 

8131 d 1.0 

8132 e NaN 

8133 dtype: float64 

8134 >>> a.subtract(b, fill_value=0) 

8135 a 0.0 

8136 b 1.0 

8137 c 1.0 

8138 d -1.0 

8139 e NaN 

8140 dtype: float64 

8141 """ 

8142 return self._flex_method( 

8143 other, operator.sub, level=level, fill_value=fill_value, axis=axis 

8144 ) 

8145 

8146 subtract = sub 

8147 

8148 def rsub(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series: 

8149 """ 

8150 Return Subtraction of series and other, element-wise (binary operator `rsub`). 

8151 

8152 Equivalent to ``other - series``, but with support to substitute a 

8153 fill_value for missing data in either one of the inputs. 

8154 

8155 Parameters 

8156 ---------- 

8157 other : object 

8158 When a Series is provided, will align on indexes. For all other types, 

8159 will behave the same as ``-`` but with possibly different results due 

8160 to the other arguments. 

8161 level : int or name 

8162 Broadcast across a level, matching Index values on the 

8163 passed MultiIndex level. 

8164 fill_value : scalar or None, default None 

8165 Fill NA values, whether present in the original data or introduced 

8166 by alignment, with this value before computation. Positions where 

8167 both inputs are NA are left unfilled and behave as NA does for the 

8168 operation. 

8169 axis : {0 or 'index'} 

8170 Unused. Parameter needed for compatibility with DataFrame. 

8171 

8172 Returns 

8173 ------- 

8174 Series 

8175 The result of the operation. 

8176 

8177 See Also 

8178 -------- 

8179 Series.sub : Element-wise Subtraction, see 

8180 `Python documentation 

8181 <https://docs.python.org/3/reference/datamodel.html#emulating-numeric-types>`_ 

8182 for more details. 

8183 

8184 Examples 

8185 -------- 

8186 >>> a = pd.Series([1, 1, 1, np.nan], index=["a", "b", "c", "d"]) 

8187 >>> a 

8188 a 1.0 

8189 b 1.0 

8190 c 1.0 

8191 d NaN 

8192 dtype: float64 

8193 >>> b = pd.Series([1, np.nan, 1, np.nan], index=["a", "b", "d", "e"]) 

8194 >>> b 

8195 a 1.0 

8196 b NaN 

8197 d 1.0 

8198 e NaN 

8199 dtype: float64 

8200 >>> a.rsub(b, fill_value=0) 

8201 a 0.0 

8202 b -1.0 

8203 c -1.0 

8204 d 1.0 

8205 e NaN 

8206 dtype: float64 

8207 """ 

8208 return self._flex_method( 

8209 other, roperator.rsub, level=level, fill_value=fill_value, axis=axis 

8210 ) 

8211 

8212 def mul( 

8213 self, 

8214 other, 

8215 level: Level | None = None, 

8216 fill_value: float | None = None, 

8217 axis: Axis = 0, 

8218 ) -> Series: 

8219 """ 

8220 Return Multiplication of series and other, element-wise (binary operator `mul`). 

8221 

8222 Equivalent to ``series * other``, but with support to substitute 

8223 a fill_value for missing data in either one of the inputs. 

8224 

8225 Parameters 

8226 ---------- 

8227 other : Series or scalar value 

8228 With which to compute the multiplication. 

8229 level : int or name 

8230 Broadcast across a level, matching Index values on the 

8231 passed MultiIndex level. 

8232 fill_value : scalar or None, default None 

8233 Fill NA values, whether present in the original data or introduced 

8234 by alignment, with this value before computation. Positions where 

8235 both inputs are NA are left unfilled and behave as NA does for the 

8236 operation. 

8237 axis : {0 or 'index'} 

8238 Unused. Parameter needed for compatibility with DataFrame. 

8239 

8240 Returns 

8241 ------- 

8242 Series 

8243 The result of the operation. 

8244 

8245 See Also 

8246 -------- 

8247 Series.rmul : Reverse of the Multiplication operator, see 

8248 `Python documentation 

8249 <https://docs.python.org/3/reference/datamodel.html#emulating-numeric-types>`_ 

8250 for more details. 

8251 

8252 Examples 

8253 -------- 

8254 >>> a = pd.Series([1, 1, 1, np.nan], index=["a", "b", "c", "d"]) 

8255 >>> a 

8256 a 1.0 

8257 b 1.0 

8258 c 1.0 

8259 d NaN 

8260 dtype: float64 

8261 >>> b = pd.Series([1, np.nan, 1, np.nan], index=["a", "b", "d", "e"]) 

8262 >>> b 

8263 a 1.0 

8264 b NaN 

8265 d 1.0 

8266 e NaN 

8267 dtype: float64 

8268 >>> a.multiply(b, fill_value=0) 

8269 a 1.0 

8270 b 0.0 

8271 c 0.0 

8272 d 0.0 

8273 e NaN 

8274 dtype: float64 

8275 >>> a.mul(5, fill_value=0) 

8276 a 5.0 

8277 b 5.0 

8278 c 5.0 

8279 d 0.0 

8280 dtype: float64 

8281 """ 

8282 return self._flex_method( 

8283 other, operator.mul, level=level, fill_value=fill_value, axis=axis 

8284 ) 

8285 

8286 multiply = mul 

8287 

8288 def rmul(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series: 

8289 """ 

8290 Return Multiplication of series and other, \ 

8291 element-wise (binary operator `rmul`). 

8292 

8293 Equivalent to ``other * series``, but with support to substitute a 

8294 fill_value for missing data in either one of the inputs. 

8295 

8296 Parameters 

8297 ---------- 

8298 other : object 

8299 When a Series is provided, will align on indexes. For all other types, 

8300 will behave the same as ``*`` but with possibly different results due 

8301 to the other arguments. 

8302 level : int or name 

8303 Broadcast across a level, matching Index values on the 

8304 passed MultiIndex level. 

8305 fill_value : scalar or None, default None 

8306 Fill NA values, whether present in the original data or introduced 

8307 by alignment, with this value before computation. Positions where 

8308 both inputs are NA are left unfilled and behave as NA does for the 

8309 operation. 

8310 axis : {0 or 'index'} 

8311 Unused. Parameter needed for compatibility with DataFrame. 

8312 

8313 Returns 

8314 ------- 

8315 Series 

8316 The result of the operation. 

8317 

8318 See Also 

8319 -------- 

8320 Series.mul : Element-wise Multiplication, see 

8321 `Python documentation 

8322 <https://docs.python.org/3/reference/datamodel.html#emulating-numeric-types>`_ 

8323 for more details. 

8324 

8325 Examples 

8326 -------- 

8327 >>> a = pd.Series([1, 1, 1, np.nan], index=["a", "b", "c", "d"]) 

8328 >>> a 

8329 a 1.0 

8330 b 1.0 

8331 c 1.0 

8332 d NaN 

8333 dtype: float64 

8334 >>> b = pd.Series([1, np.nan, 1, np.nan], index=["a", "b", "d", "e"]) 

8335 >>> b 

8336 a 1.0 

8337 b NaN 

8338 d 1.0 

8339 e NaN 

8340 dtype: float64 

8341 >>> a.rmul(b, fill_value=0) 

8342 a 1.0 

8343 b 0.0 

8344 c 0.0 

8345 d 0.0 

8346 e NaN 

8347 dtype: float64 

8348 """ 

8349 return self._flex_method( 

8350 other, roperator.rmul, level=level, fill_value=fill_value, axis=axis 

8351 ) 

8352 

8353 def truediv(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series: 

8354 """ 

8355 Return Floating division of series and other, \ 

8356 element-wise (binary operator `truediv`). 

8357 

8358 Equivalent to ``series / other``, but with support to substitute a 

8359 fill_value for missing data in either one of the inputs. 

8360 

8361 Parameters 

8362 ---------- 

8363 other : Series or scalar value 

8364 Series with which to compute division. 

8365 level : int or name 

8366 Broadcast across a level, matching Index values on the 

8367 passed MultiIndex level. 

8368 fill_value : scalar or None, default None 

8369 Fill NA values, whether present in the original data or introduced 

8370 by alignment, with this value before computation. Positions where 

8371 both inputs are NA are left unfilled and behave as NA does for the 

8372 operation. 

8373 axis : {0 or 'index'} 

8374 Unused. Parameter needed for compatibility with DataFrame. 

8375 

8376 Returns 

8377 ------- 

8378 Series 

8379 The result of the operation. 

8380 

8381 See Also 

8382 -------- 

8383 Series.rtruediv : Reverse of the Floating division operator, see 

8384 `Python documentation 

8385 <https://docs.python.org/3/reference/datamodel.html#emulating-numeric-types>`_ 

8386 for more details. 

8387 

8388 Examples 

8389 -------- 

8390 >>> a = pd.Series([1, 1, 1, np.nan], index=["a", "b", "c", "d"]) 

8391 >>> a 

8392 a 1.0 

8393 b 1.0 

8394 c 1.0 

8395 d NaN 

8396 dtype: float64 

8397 >>> b = pd.Series([1, np.nan, 1, np.nan], index=["a", "b", "d", "e"]) 

8398 >>> b 

8399 a 1.0 

8400 b NaN 

8401 d 1.0 

8402 e NaN 

8403 dtype: float64 

8404 >>> a.divide(b, fill_value=0) 

8405 a 1.0 

8406 b inf 

8407 c inf 

8408 d 0.0 

8409 e NaN 

8410 dtype: float64 

8411 """ 

8412 return self._flex_method( 

8413 other, operator.truediv, level=level, fill_value=fill_value, axis=axis 

8414 ) 

8415 

8416 div = truediv 

8417 divide = truediv 

8418 

8419 def rtruediv(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series: 

8420 """ 

8421 Return Floating division of series and other, \ 

8422 element-wise (binary operator `rtruediv`). 

8423 

8424 Equivalent to ``other / series``, but with support to substitute a 

8425 fill_value for missing data in either one of the inputs. 

8426 

8427 Parameters 

8428 ---------- 

8429 other : object 

8430 When a Series is provided, will align on indexes. For all other types, 

8431 will behave the same as ``/`` but with possibly different results due 

8432 to the other arguments. 

8433 level : int or name 

8434 Broadcast across a level, matching Index values on the 

8435 passed MultiIndex level. 

8436 fill_value : scalar or None, default None 

8437 Fill NA values, whether present in the original data or introduced 

8438 by alignment, with this value before computation. Positions where 

8439 both inputs are NA are left unfilled and behave as NA does for the 

8440 operation. 

8441 axis : {0 or 'index'} 

8442 Unused. Parameter needed for compatibility with DataFrame. 

8443 

8444 Returns 

8445 ------- 

8446 Series 

8447 The result of the operation. 

8448 

8449 See Also 

8450 -------- 

8451 Series.truediv : Element-wise Floating division, see 

8452 `Python documentation 

8453 <https://docs.python.org/3/reference/datamodel.html#emulating-numeric-types>`_ 

8454 for more details. 

8455 

8456 Examples 

8457 -------- 

8458 >>> a = pd.Series([1, 1, 1, np.nan], index=["a", "b", "c", "d"]) 

8459 >>> a 

8460 a 1.0 

8461 b 1.0 

8462 c 1.0 

8463 d NaN 

8464 dtype: float64 

8465 >>> b = pd.Series([1, np.nan, 1, np.nan], index=["a", "b", "d", "e"]) 

8466 >>> b 

8467 a 1.0 

8468 b NaN 

8469 d 1.0 

8470 e NaN 

8471 dtype: float64 

8472 >>> a.rtruediv(b, fill_value=0) 

8473 a 1.0 

8474 b 0.0 

8475 c 0.0 

8476 d inf 

8477 e NaN 

8478 dtype: float64 

8479 """ 

8480 return self._flex_method( 

8481 other, roperator.rtruediv, level=level, fill_value=fill_value, axis=axis 

8482 ) 

8483 

8484 rdiv = rtruediv 

8485 

8486 def floordiv(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series: 

8487 """ 

8488 Return Integer division of series and other, \ 

8489 element-wise (binary operator `floordiv`). 

8490 

8491 Equivalent to ``series // other``, but with support to substitute a 

8492 fill_value for missing data in either one of the inputs. 

8493 

8494 Parameters 

8495 ---------- 

8496 other : object 

8497 When a Series is provided, will align on indexes. For all other types, 

8498 will behave the same as ``//`` but with possibly different results due 

8499 to the other arguments. 

8500 level : int or name 

8501 Broadcast across a level, matching Index values on the 

8502 passed MultiIndex level. 

8503 fill_value : scalar or None, default None 

8504 Fill NA values, whether present in the original data or introduced 

8505 by alignment, with this value before computation. Positions where 

8506 both inputs are NA are left unfilled and behave as NA does for the 

8507 operation. 

8508 axis : {0 or 'index'} 

8509 Unused. Parameter needed for compatibility with DataFrame. 

8510 

8511 Returns 

8512 ------- 

8513 Series 

8514 The result of the operation. 

8515 

8516 See Also 

8517 -------- 

8518 Series.rfloordiv : Reverse of the Integer division operator, see 

8519 `Python documentation 

8520 <https://docs.python.org/3/reference/datamodel.html#emulating-numeric-types>`_ 

8521 for more details. 

8522 

8523 Examples 

8524 -------- 

8525 >>> a = pd.Series([1, 1, 1, np.nan], index=["a", "b", "c", "d"]) 

8526 >>> a 

8527 a 1.0 

8528 b 1.0 

8529 c 1.0 

8530 d NaN 

8531 dtype: float64 

8532 >>> b = pd.Series([1, np.nan, 1, np.nan], index=["a", "b", "d", "e"]) 

8533 >>> b 

8534 a 1.0 

8535 b NaN 

8536 d 1.0 

8537 e NaN 

8538 dtype: float64 

8539 >>> a.floordiv(b, fill_value=0) 

8540 a 1.0 

8541 b inf 

8542 c inf 

8543 d 0.0 

8544 e NaN 

8545 dtype: float64 

8546 """ 

8547 return self._flex_method( 

8548 other, operator.floordiv, level=level, fill_value=fill_value, axis=axis 

8549 ) 

8550 

8551 def rfloordiv(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series: 

8552 """ 

8553 Return Integer division of series and other, \ 

8554 element-wise (binary operator `rfloordiv`). 

8555 

8556 Equivalent to ``other // series``, but with support to substitute a 

8557 fill_value for missing data in either one of the inputs. 

8558 

8559 Parameters 

8560 ---------- 

8561 other : object 

8562 When a Series is provided, will align on indexes. For all other types, 

8563 will behave the same as ``//`` but with possibly different results due 

8564 to the other arguments. 

8565 level : int or name 

8566 Broadcast across a level, matching Index values on the 

8567 passed MultiIndex level. 

8568 fill_value : scalar or None, default None 

8569 Fill NA values, whether present in the original data or introduced 

8570 by alignment, with this value before computation. Positions where 

8571 both inputs are NA are left unfilled and behave as NA does for the 

8572 operation. 

8573 axis : {0 or 'index'} 

8574 Unused. Parameter needed for compatibility with DataFrame. 

8575 

8576 Returns 

8577 ------- 

8578 Series 

8579 The result of the operation. 

8580 

8581 See Also 

8582 -------- 

8583 Series.floordiv : Element-wise Integer division, see 

8584 `Python documentation 

8585 <https://docs.python.org/3/reference/datamodel.html#emulating-numeric-types>`_ 

8586 for more details. 

8587 

8588 Examples 

8589 -------- 

8590 >>> a = pd.Series([1, 1, 1, np.nan], index=["a", "b", "c", "d"]) 

8591 >>> a 

8592 a 1.0 

8593 b 1.0 

8594 c 1.0 

8595 d NaN 

8596 dtype: float64 

8597 >>> b = pd.Series([1, np.nan, 1, np.nan], index=["a", "b", "d", "e"]) 

8598 >>> b 

8599 a 1.0 

8600 b NaN 

8601 d 1.0 

8602 e NaN 

8603 dtype: float64 

8604 >>> a.rfloordiv(b, fill_value=0) 

8605 a 1.0 

8606 b 0.0 

8607 c 0.0 

8608 d inf 

8609 e NaN 

8610 dtype: float64 

8611 """ 

8612 return self._flex_method( 

8613 other, roperator.rfloordiv, level=level, fill_value=fill_value, axis=axis 

8614 ) 

8615 

8616 def mod(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series: 

8617 """ 

8618 Return Modulo of series and other, element-wise (binary operator `mod`). 

8619 

8620 Equivalent to ``series % other``, but with support to substitute a 

8621 fill_value for missing data in either one of the inputs. 

8622 

8623 Parameters 

8624 ---------- 

8625 other : Series or scalar value 

8626 Series with which to compute modulo. 

8627 level : int or name 

8628 Broadcast across a level, matching Index values on the 

8629 passed MultiIndex level. 

8630 fill_value : scalar or None, default None 

8631 Fill NA values, whether present in the original data or introduced 

8632 by alignment, with this value before computation. Positions where 

8633 both inputs are NA are left unfilled and behave as NA does for the 

8634 operation. 

8635 axis : {0 or 'index'} 

8636 Unused. Parameter needed for compatibility with DataFrame. 

8637 

8638 Returns 

8639 ------- 

8640 Series 

8641 The result of the operation. 

8642 

8643 See Also 

8644 -------- 

8645 Series.rmod : Reverse of the Modulo operator, see 

8646 `Python documentation 

8647 <https://docs.python.org/3/reference/datamodel.html#emulating-numeric-types>`_ 

8648 for more details. 

8649 

8650 Examples 

8651 -------- 

8652 >>> a = pd.Series([1, 1, 1, np.nan], index=["a", "b", "c", "d"]) 

8653 >>> a 

8654 a 1.0 

8655 b 1.0 

8656 c 1.0 

8657 d NaN 

8658 dtype: float64 

8659 >>> b = pd.Series([1, np.nan, 1, np.nan], index=["a", "b", "d", "e"]) 

8660 >>> b 

8661 a 1.0 

8662 b NaN 

8663 d 1.0 

8664 e NaN 

8665 dtype: float64 

8666 >>> a.mod(b, fill_value=0) 

8667 a 0.0 

8668 b NaN 

8669 c NaN 

8670 d 0.0 

8671 e NaN 

8672 dtype: float64 

8673 """ 

8674 return self._flex_method( 

8675 other, operator.mod, level=level, fill_value=fill_value, axis=axis 

8676 ) 

8677 

8678 def rmod(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series: 

8679 """ 

8680 Return Modulo of series and other, \ 

8681 element-wise (binary operator `rmod`). 

8682 

8683 Equivalent to ``other % series``, but with support to substitute a 

8684 fill_value for missing data in either one of the inputs. 

8685 

8686 Parameters 

8687 ---------- 

8688 other : object 

8689 When a Series is provided, will align on indexes. For all other types, 

8690 will behave the same as ``%`` but with possibly different results due 

8691 to the other arguments. 

8692 level : int or name 

8693 Broadcast across a level, matching Index values on the 

8694 passed MultiIndex level. 

8695 fill_value : scalar or None, default None 

8696 Fill NA values, whether present in the original data or introduced 

8697 by alignment, with this value before computation. Positions where 

8698 both inputs are NA are left unfilled and behave as NA does for the 

8699 operation. 

8700 axis : {0 or 'index'} 

8701 Unused. Parameter needed for compatibility with DataFrame. 

8702 

8703 Returns 

8704 ------- 

8705 Series 

8706 The result of the operation. 

8707 

8708 See Also 

8709 -------- 

8710 Series.mod : Element-wise Modulo, see 

8711 `Python documentation 

8712 <https://docs.python.org/3/reference/datamodel.html#emulating-numeric-types>`_ 

8713 for more details. 

8714 

8715 Examples 

8716 -------- 

8717 >>> a = pd.Series([1, 1, 1, np.nan], index=["a", "b", "c", "d"]) 

8718 >>> a 

8719 a 1.0 

8720 b 1.0 

8721 c 1.0 

8722 d NaN 

8723 dtype: float64 

8724 >>> b = pd.Series([1, np.nan, 1, np.nan], index=["a", "b", "d", "e"]) 

8725 >>> b 

8726 a 1.0 

8727 b NaN 

8728 d 1.0 

8729 e NaN 

8730 dtype: float64 

8731 >>> a.rmod(b, fill_value=0) 

8732 a 0.0 

8733 b 0.0 

8734 c 0.0 

8735 d NaN 

8736 e NaN 

8737 dtype: float64 

8738 """ 

8739 return self._flex_method( 

8740 other, roperator.rmod, level=level, fill_value=fill_value, axis=axis 

8741 ) 

8742 

8743 def pow(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series: 

8744 """ 

8745 Return Exponential power of series and other, \ 

8746 element-wise (binary operator `pow`). 

8747 

8748 Equivalent to ``series ** other``, but with support to substitute a 

8749 fill_value for missing data in either one of the inputs. 

8750 

8751 Parameters 

8752 ---------- 

8753 other : object 

8754 When a Series is provided, will align on indexes. For all other types, 

8755 will behave the same as ``**`` but with possibly different results due 

8756 to the other arguments. 

8757 level : int or name 

8758 Broadcast across a level, matching Index values on the 

8759 passed MultiIndex level. 

8760 fill_value : scalar or None, default None 

8761 Fill NA values, whether present in the original data or introduced 

8762 by alignment, with this value before computation. Positions where 

8763 both inputs are NA are left unfilled and behave as NA does for the 

8764 operation. 

8765 axis : {0 or 'index'} 

8766 Unused. Parameter needed for compatibility with DataFrame. 

8767 

8768 Returns 

8769 ------- 

8770 Series 

8771 The result of the operation. 

8772 

8773 See Also 

8774 -------- 

8775 Series.rpow : Reverse of the Exponential power operator, see 

8776 `Python documentation 

8777 <https://docs.python.org/3/reference/datamodel.html#emulating-numeric-types>`_ 

8778 for more details. 

8779 

8780 Examples 

8781 -------- 

8782 >>> a = pd.Series([1, 1, 1, np.nan], index=["a", "b", "c", "d"]) 

8783 >>> a 

8784 a 1.0 

8785 b 1.0 

8786 c 1.0 

8787 d NaN 

8788 dtype: float64 

8789 >>> b = pd.Series([1, np.nan, 1, np.nan], index=["a", "b", "d", "e"]) 

8790 >>> b 

8791 a 1.0 

8792 b NaN 

8793 d 1.0 

8794 e NaN 

8795 dtype: float64 

8796 >>> a.pow(b, fill_value=0) 

8797 a 1.0 

8798 b 1.0 

8799 c 1.0 

8800 d 0.0 

8801 e NaN 

8802 dtype: float64 

8803 """ 

8804 return self._flex_method( 

8805 other, operator.pow, level=level, fill_value=fill_value, axis=axis 

8806 ) 

8807 

8808 def rpow(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series: 

8809 """ 

8810 Return Exponential power of series and other, \ 

8811 element-wise (binary operator `rpow`). 

8812 

8813 Equivalent to ``other ** series``, but with support to substitute a 

8814 fill_value for missing data in either one of the inputs. 

8815 

8816 Parameters 

8817 ---------- 

8818 other : object 

8819 When a Series is provided, will align on indexes. For all other types, 

8820 will behave the same as ``**`` but with possibly different results due 

8821 to the other arguments. 

8822 level : int or name 

8823 Broadcast across a level, matching Index values on the 

8824 passed MultiIndex level. 

8825 fill_value : scalar or None, default None 

8826 Fill NA values, whether present in the original data or introduced 

8827 by alignment, with this value before computation. Positions where 

8828 both inputs are NA are left unfilled and behave as NA does for the 

8829 operation. 

8830 axis : {0 or 'index'} 

8831 Unused. Parameter needed for compatibility with DataFrame. 

8832 

8833 Returns 

8834 ------- 

8835 Series 

8836 The result of the operation. 

8837 

8838 See Also 

8839 -------- 

8840 Series.pow : Element-wise Exponential power, see 

8841 `Python documentation 

8842 <https://docs.python.org/3/reference/datamodel.html#emulating-numeric-types>`_ 

8843 for more details. 

8844 

8845 Examples 

8846 -------- 

8847 >>> a = pd.Series([1, 1, 1, np.nan], index=["a", "b", "c", "d"]) 

8848 >>> a 

8849 a 1.0 

8850 b 1.0 

8851 c 1.0 

8852 d NaN 

8853 dtype: float64 

8854 >>> b = pd.Series([1, np.nan, 1, np.nan], index=["a", "b", "d", "e"]) 

8855 >>> b 

8856 a 1.0 

8857 b NaN 

8858 d 1.0 

8859 e NaN 

8860 dtype: float64 

8861 >>> a.rpow(b, fill_value=0) 

8862 a 1.0 

8863 b 0.0 

8864 c 0.0 

8865 d 1.0 

8866 e NaN 

8867 dtype: float64 

8868 """ 

8869 return self._flex_method( 

8870 other, roperator.rpow, level=level, fill_value=fill_value, axis=axis 

8871 ) 

8872 

8873 def divmod(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series: 

8874 """ 

8875 Return Integer division and modulo of series and other, \ 

8876 element-wise (binary operator `divmod`). 

8877 

8878 Equivalent to ``divmod(series, other)``, but with support to substitute a 

8879 fill_value for missing data in either one of the inputs. 

8880 

8881 Parameters 

8882 ---------- 

8883 other : object 

8884 When a Series is provided, will align on indexes. For all other types, 

8885 will behave the same as ``//`` and ``%`` but with possibly different 

8886 results due to the other arguments. 

8887 level : int or name 

8888 Broadcast across a level, matching Index values on the 

8889 passed MultiIndex level. 

8890 fill_value : scalar or None, default None 

8891 Fill NA values, whether present in the original data or introduced 

8892 by alignment, with this value before computation. Positions where 

8893 both inputs are NA are left unfilled and behave as NA does for the 

8894 operation. 

8895 axis : {0 or 'index'} 

8896 Unused. Parameter needed for compatibility with DataFrame. 

8897 

8898 Returns 

8899 ------- 

8900 2-Tuple of Series 

8901 The result of the operation. 

8902 

8903 See Also 

8904 -------- 

8905 Series.rdivmod : Reverse of the Integer division and modulo operator, see 

8906 `Python documentation 

8907 <https://docs.python.org/3/reference/datamodel.html#emulating-numeric-types>`_ 

8908 for more details. 

8909 

8910 Examples 

8911 -------- 

8912 >>> a = pd.Series([1, 1, 1, np.nan], index=["a", "b", "c", "d"]) 

8913 >>> a 

8914 a 1.0 

8915 b 1.0 

8916 c 1.0 

8917 d NaN 

8918 dtype: float64 

8919 >>> b = pd.Series([1, np.nan, 1, np.nan], index=["a", "b", "d", "e"]) 

8920 >>> b 

8921 a 1.0 

8922 b NaN 

8923 d 1.0 

8924 e NaN 

8925 dtype: float64 

8926 >>> a.divmod(b, fill_value=0) 

8927 (a 1.0 

8928 b inf 

8929 c inf 

8930 d 0.0 

8931 e NaN 

8932 dtype: float64, 

8933 a 0.0 

8934 b NaN 

8935 c NaN 

8936 d 0.0 

8937 e NaN 

8938 dtype: float64) 

8939 """ 

8940 return self._flex_method( 

8941 other, divmod, level=level, fill_value=fill_value, axis=axis 

8942 ) 

8943 

8944 def rdivmod(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series: 

8945 """ 

8946 Return Integer division and modulo of series and other, \ 

8947 element-wise (binary operator `rdivmod`). 

8948 

8949 Equivalent to ``other divmod series``, but with support to substitute a 

8950 fill_value for missing data in either one of the inputs. 

8951 

8952 Parameters 

8953 ---------- 

8954 other : object 

8955 When a Series is provided, will align on indexes. For all other types, 

8956 will behave the same as ``//`` and ``%`` but with possibly different 

8957 results due to the other arguments. 

8958 level : int or name 

8959 Broadcast across a level, matching Index values on the 

8960 passed MultiIndex level. 

8961 fill_value : scalar or None, default None 

8962 Fill NA values, whether present in the original data or introduced 

8963 by alignment, with this value before computation. Positions where 

8964 both inputs are NA are left unfilled and behave as NA does for the 

8965 operation. 

8966 axis : {0 or 'index'} 

8967 Unused. Parameter needed for compatibility with DataFrame. 

8968 

8969 Returns 

8970 ------- 

8971 2-Tuple of Series 

8972 The result of the operation. 

8973 

8974 See Also 

8975 -------- 

8976 Series.divmod : Element-wise Integer division and modulo, see 

8977 `Python documentation 

8978 <https://docs.python.org/3/reference/datamodel.html#emulating-numeric-types>`_ 

8979 for more details. 

8980 

8981 Examples 

8982 -------- 

8983 >>> a = pd.Series([1, 1, 1, np.nan], index=["a", "b", "c", "d"]) 

8984 >>> a 

8985 a 1.0 

8986 b 1.0 

8987 c 1.0 

8988 d NaN 

8989 dtype: float64 

8990 >>> b = pd.Series([1, np.nan, 1, np.nan], index=["a", "b", "d", "e"]) 

8991 >>> b 

8992 a 1.0 

8993 b NaN 

8994 d 1.0 

8995 e NaN 

8996 dtype: float64 

8997 >>> a.rdivmod(b, fill_value=0) 

8998 (a 1.0 

8999 b 0.0 

9000 c 0.0 

9001 d inf 

9002 e NaN 

9003 dtype: float64, 

9004 a 0.0 

9005 b 0.0 

9006 c 0.0 

9007 d NaN 

9008 e NaN 

9009 dtype: float64) 

9010 """ 

9011 return self._flex_method( 

9012 other, roperator.rdivmod, level=level, fill_value=fill_value, axis=axis 

9013 ) 

9014 

9015 # ---------------------------------------------------------------------- 

9016 # Reductions 

9017 

9018 def _reduce( 

9019 self, 

9020 op, 

9021 # error: Variable "pandas.core.series.Series.str" is not valid as a type 

9022 name: str, # type: ignore[valid-type] 

9023 *, 

9024 axis: Axis = 0, 

9025 skipna: bool = True, 

9026 numeric_only: bool = False, 

9027 filter_type=None, 

9028 **kwds, 

9029 ): 

9030 """ 

9031 Perform a reduction operation. 

9032 

9033 If we have an ndarray as a value, then simply perform the operation, 

9034 otherwise delegate to the object. 

9035 """ 

9036 delegate = self._values 

9037 

9038 if axis is not None: 

9039 self._get_axis_number(axis) 

9040 

9041 if isinstance(delegate, ExtensionArray): 

9042 # dispatch to ExtensionArray interface 

9043 result = delegate._reduce(name, skipna=skipna, **kwds) 

9044 

9045 else: 

9046 # dispatch to numpy arrays 

9047 if numeric_only and self.dtype.kind not in "iufcb": 

9048 # i.e. not is_numeric_dtype(self.dtype) 

9049 kwd_name = "numeric_only" 

9050 if name in ["any", "all"]: 

9051 kwd_name = "bool_only" 

9052 # GH#47500 - change to TypeError to match other methods 

9053 raise TypeError( 

9054 f"Series.{name} does not allow {kwd_name}={numeric_only} " 

9055 "with non-numeric dtypes." 

9056 ) 

9057 result = op(delegate, skipna=skipna, **kwds) 

9058 

9059 # any/all coerce to bool for all dtypes, so unbox even for object 

9060 result = maybe_unbox_numpy_scalar( 

9061 result, object_with_dtype=None if name in ["any", "all"] else self 

9062 ) 

9063 return result 

9064 

9065 # error: Signature of "any" incompatible with supertype "NDFrame" 

9066 def any( # type: ignore[override] 

9067 self, 

9068 *, 

9069 axis: Axis = 0, 

9070 bool_only: bool = False, 

9071 skipna: bool = True, 

9072 **kwargs, 

9073 ) -> bool: 

9074 """ 

9075 Return whether any element is True, potentially over an axis. 

9076 

9077 Returns False unless there is at least one element within a series or 

9078 along a Dataframe axis that is True or equivalent (e.g. non-zero or 

9079 non-empty). 

9080 

9081 Parameters 

9082 ---------- 

9083 axis : {0 or 'index', 1 or 'columns', None}, default 0 

9084 Indicate which axis or axes should be reduced. For `Series` this parameter 

9085 is unused and defaults to 0. 

9086 

9087 * 0 / 'index' : reduce the index, return a Series whose index is the 

9088 original column labels. 

9089 * 1 / 'columns' : reduce the columns, return a Series whose index is the 

9090 original index. 

9091 * None : reduce all axes, return a scalar. 

9092 

9093 bool_only : bool, default False 

9094 Include only boolean columns. Not implemented for Series. 

9095 skipna : bool, default True 

9096 Exclude NA/null values. If the entire row/column is NA and skipna is 

9097 True, then the result will be False, as for an empty row/column. 

9098 If skipna is False, NA values are treated as True for NumPy-backed 

9099 dtypes (since they are not equal to zero). For nullable dtypes such 

9100 as ``boolean``, NA values propagate following 

9101 :ref:`Kleene logic <boolean.kleene>`. 

9102 **kwargs : any, default None 

9103 Additional keywords have no effect but might be accepted for 

9104 compatibility with NumPy. See :ref:`gotchas.numpy_kwargs` for more. 

9105 

9106 Returns 

9107 ------- 

9108 Series or scalar 

9109 If axis=None, then a scalar boolean is returned. 

9110 Otherwise a Series is returned with index matching the index argument. 

9111 

9112 See Also 

9113 -------- 

9114 numpy.any : Numpy version of this method. 

9115 Series.any : Return whether any element is True. 

9116 Series.all : Return whether all elements are True. 

9117 DataFrame.any : Return whether any element is True over requested axis. 

9118 DataFrame.all : Return whether all elements are True over requested axis. 

9119 

9120 Examples 

9121 -------- 

9122 **Series** 

9123 

9124 For Series input, the output is a scalar indicating whether any element 

9125 is True. 

9126 

9127 >>> pd.Series([False, False]).any() 

9128 False 

9129 >>> pd.Series([True, False]).any() 

9130 True 

9131 >>> pd.Series([], dtype="float64").any() 

9132 False 

9133 >>> pd.Series([np.nan]).any() 

9134 False 

9135 >>> pd.Series([np.nan]).any(skipna=False) 

9136 True 

9137 

9138 **DataFrame** 

9139 

9140 Whether each column contains at least one True element (the default). 

9141 

9142 >>> df = pd.DataFrame({"A": [1, 2], "B": [0, 2], "C": [0, 0]}) 

9143 >>> df 

9144 A B C 

9145 0 1 0 0 

9146 1 2 2 0 

9147 

9148 >>> df.any() 

9149 A True 

9150 B True 

9151 C False 

9152 dtype: bool 

9153 

9154 Aggregating over the columns. 

9155 

9156 >>> df = pd.DataFrame({"A": [True, False], "B": [1, 2]}) 

9157 >>> df 

9158 A B 

9159 0 True 1 

9160 1 False 2 

9161 

9162 >>> df.any(axis="columns") 

9163 0 True 

9164 1 True 

9165 dtype: bool 

9166 

9167 >>> df = pd.DataFrame({"A": [True, False], "B": [1, 0]}) 

9168 >>> df 

9169 A B 

9170 0 True 1 

9171 1 False 0 

9172 

9173 >>> df.any(axis="columns") 

9174 0 True 

9175 1 False 

9176 dtype: bool 

9177 

9178 Aggregating over the entire DataFrame with ``axis=None``. 

9179 

9180 >>> df.any(axis=None) 

9181 True 

9182 

9183 `any` for an empty DataFrame is an empty Series. 

9184 

9185 >>> pd.DataFrame([]).any() 

9186 Series([], dtype: bool) 

9187 """ 

9188 nv.validate_logical_func((), kwargs, fname="any") 

9189 validate_bool_kwarg(skipna, "skipna", none_allowed=False) 

9190 return self._reduce( 

9191 nanops.nanany, 

9192 name="any", 

9193 axis=axis, 

9194 numeric_only=bool_only, 

9195 skipna=skipna, 

9196 filter_type="bool", 

9197 ) 

9198 

9199 @deprecate_nonkeyword_arguments(Pandas4Warning, allowed_args=["self"], name="all") 

9200 def all( 

9201 self, 

9202 axis: Axis = 0, 

9203 bool_only: bool = False, 

9204 skipna: bool = True, 

9205 **kwargs, 

9206 ) -> bool: 

9207 """ 

9208 Return whether all elements are True, potentially over an axis. 

9209 

9210 Returns True unless there at least one element within a series or 

9211 along a Dataframe axis that is False or equivalent (e.g. zero or 

9212 empty). 

9213 

9214 Parameters 

9215 ---------- 

9216 axis : {0 or 'index', 1 or 'columns', None}, default 0 

9217 Indicate which axis or axes should be reduced. For `Series` this parameter 

9218 is unused and defaults to 0. 

9219 

9220 * 0 / 'index' : reduce the index, return a Series whose index is the 

9221 original column labels. 

9222 * 1 / 'columns' : reduce the columns, return a Series whose index is the 

9223 original index. 

9224 * None : reduce all axes, return a scalar. 

9225 

9226 bool_only : bool, default False 

9227 Include only boolean columns. Not implemented for Series. 

9228 skipna : bool, default True 

9229 Exclude NA/null values. If the entire row/column is NA and skipna is 

9230 True, then the result will be True, as for an empty row/column. 

9231 If skipna is False, NA values are treated as True for NumPy-backed 

9232 dtypes (since they are not equal to zero). For nullable dtypes such 

9233 as ``boolean``, NA values propagate following 

9234 :ref:`Kleene logic <boolean.kleene>`. 

9235 **kwargs : any, default None 

9236 Additional keywords have no effect but might be accepted for 

9237 compatibility with NumPy. See :ref:`gotchas.numpy_kwargs` for more. 

9238 

9239 Returns 

9240 ------- 

9241 Series or scalar 

9242 If axis=None, then a scalar boolean is returned. 

9243 Otherwise a Series is returned with index matching the index argument. 

9244 

9245 See Also 

9246 -------- 

9247 Series.all : Return True if all elements are True. 

9248 DataFrame.any : Return True if one (or more) elements are True. 

9249 

9250 Examples 

9251 -------- 

9252 **Series** 

9253 

9254 >>> pd.Series([True, True]).all() 

9255 True 

9256 >>> pd.Series([True, False]).all() 

9257 False 

9258 >>> pd.Series([], dtype="float64").all() 

9259 True 

9260 >>> pd.Series([np.nan]).all() 

9261 True 

9262 >>> pd.Series([np.nan]).all(skipna=False) 

9263 True 

9264 

9265 **DataFrames** 

9266 

9267 Create a DataFrame from a dictionary. 

9268 

9269 >>> df = pd.DataFrame({"col1": [True, True], "col2": [True, False]}) 

9270 >>> df 

9271 col1 col2 

9272 0 True True 

9273 1 True False 

9274 

9275 Default behaviour checks if values in each column all return True. 

9276 

9277 >>> df.all() 

9278 col1 True 

9279 col2 False 

9280 dtype: bool 

9281 

9282 Specify ``axis='columns'`` to check if values in each row all return True. 

9283 

9284 >>> df.all(axis="columns") 

9285 0 True 

9286 1 False 

9287 dtype: bool 

9288 

9289 Or ``axis=None`` for whether every value is True. 

9290 

9291 >>> df.all(axis=None) 

9292 False 

9293 """ 

9294 nv.validate_logical_func((), kwargs, fname="all") 

9295 validate_bool_kwarg(skipna, "skipna", none_allowed=False) 

9296 return self._reduce( 

9297 nanops.nanall, 

9298 name="all", 

9299 axis=axis, 

9300 numeric_only=bool_only, 

9301 skipna=skipna, 

9302 filter_type="bool", 

9303 ) 

9304 

9305 @deprecate_nonkeyword_arguments(Pandas4Warning, allowed_args=["self"], name="min") 

9306 def min( 

9307 self, 

9308 axis: Axis | None = 0, 

9309 skipna: bool = True, 

9310 numeric_only: bool = False, 

9311 **kwargs, 

9312 ): 

9313 """ 

9314 Return the minimum of the values over the requested axis. 

9315 

9316 If you want the *index* of the minimum, use ``idxmin``. 

9317 This is the equivalent of the ``numpy.ndarray`` method ``argmin``. 

9318 

9319 Parameters 

9320 ---------- 

9321 axis : {index (0)} 

9322 Axis for the function to be applied on. 

9323 For `Series` this parameter is unused and defaults to 0. 

9324 

9325 For DataFrames, specifying ``axis=None`` will apply the aggregation 

9326 across both axes. 

9327 

9328 .. versionadded:: 2.0.0 

9329 

9330 skipna : bool, default True 

9331 Exclude NA/null values when computing the result. 

9332 numeric_only : bool, default False 

9333 Include only float, int, boolean columns. 

9334 **kwargs 

9335 Additional keyword arguments have no effect but might be accepted for 

9336 compatibility with NumPy. See :ref:`gotchas.numpy_kwargs` for more. 

9337 

9338 Returns 

9339 ------- 

9340 scalar 

9341 The minimum of the values in the Series. 

9342 

9343 See Also 

9344 -------- 

9345 numpy.min : Equivalent numpy function for arrays. 

9346 Series.min : Return the minimum. 

9347 Series.max : Return the maximum. 

9348 Series.idxmin : Return the index of the minimum. 

9349 Series.idxmax : Return the index of the maximum. 

9350 DataFrame.min : Return the minimum over the requested axis. 

9351 DataFrame.max : Return the maximum over the requested axis. 

9352 DataFrame.idxmin : Return the index of the minimum over the requested axis. 

9353 DataFrame.idxmax : Return the index of the maximum over the requested axis. 

9354 

9355 Examples 

9356 -------- 

9357 >>> idx = pd.MultiIndex.from_arrays( 

9358 ... [["warm", "warm", "cold", "cold"], ["dog", "falcon", "fish", "spider"]], 

9359 ... names=["blooded", "animal"], 

9360 ... ) 

9361 >>> s = pd.Series([4, 2, 0, 8], name="legs", index=idx) 

9362 >>> s 

9363 blooded animal 

9364 warm dog 4 

9365 falcon 2 

9366 cold fish 0 

9367 spider 8 

9368 Name: legs, dtype: int64 

9369 

9370 >>> s.min() 

9371 0 

9372 """ 

9373 return NDFrame.min( 

9374 self, axis=axis, skipna=skipna, numeric_only=numeric_only, **kwargs 

9375 ) 

9376 

9377 @deprecate_nonkeyword_arguments(Pandas4Warning, allowed_args=["self"], name="max") 

9378 def max( 

9379 self, 

9380 axis: Axis | None = 0, 

9381 skipna: bool = True, 

9382 numeric_only: bool = False, 

9383 **kwargs, 

9384 ): 

9385 """ 

9386 Return the maximum of the values over the requested axis. 

9387 

9388 If you want the *index* of the maximum, use ``idxmax``. 

9389 This is the equivalent of the ``numpy.ndarray`` method ``argmax``. 

9390 

9391 Parameters 

9392 ---------- 

9393 axis : {index (0)} 

9394 Axis for the function to be applied on. 

9395 For `Series` this parameter is unused and defaults to 0. 

9396 

9397 For DataFrames, specifying ``axis=None`` will apply the aggregation 

9398 across both axes. 

9399 

9400 .. versionadded:: 2.0.0 

9401 

9402 skipna : bool, default True 

9403 Exclude NA/null values when computing the result. 

9404 numeric_only : bool, default False 

9405 Include only float, int, boolean columns. 

9406 **kwargs 

9407 Additional keyword arguments have no effect but might be accepted for 

9408 compatibility with NumPy. See :ref:`gotchas.numpy_kwargs` for more. 

9409 

9410 Returns 

9411 ------- 

9412 scalar 

9413 The maximum of the values in the Series. 

9414 

9415 See Also 

9416 -------- 

9417 numpy.max : Equivalent numpy function for arrays. 

9418 Series.min : Return the minimum. 

9419 Series.max : Return the maximum. 

9420 Series.idxmin : Return the index of the minimum. 

9421 Series.idxmax : Return the index of the maximum. 

9422 DataFrame.min : Return the minimum over the requested axis. 

9423 DataFrame.max : Return the maximum over the requested axis. 

9424 DataFrame.idxmin : Return the index of the minimum over the requested axis. 

9425 DataFrame.idxmax : Return the index of the maximum over the requested axis. 

9426 

9427 Examples 

9428 -------- 

9429 >>> idx = pd.MultiIndex.from_arrays( 

9430 ... [["warm", "warm", "cold", "cold"], ["dog", "falcon", "fish", "spider"]], 

9431 ... names=["blooded", "animal"], 

9432 ... ) 

9433 >>> s = pd.Series([4, 2, 0, 8], name="legs", index=idx) 

9434 >>> s 

9435 blooded animal 

9436 warm dog 4 

9437 falcon 2 

9438 cold fish 0 

9439 spider 8 

9440 Name: legs, dtype: int64 

9441 

9442 >>> s.max() 

9443 8 

9444 """ 

9445 return NDFrame.max( 

9446 self, axis=axis, skipna=skipna, numeric_only=numeric_only, **kwargs 

9447 ) 

9448 

9449 @deprecate_nonkeyword_arguments(Pandas4Warning, allowed_args=["self"], name="sum") 

9450 def sum( 

9451 self, 

9452 axis: Axis | None = None, 

9453 skipna: bool = True, 

9454 numeric_only: bool = False, 

9455 min_count: int = 0, 

9456 **kwargs, 

9457 ): 

9458 """ 

9459 Return the sum of the values over the requested axis. 

9460 

9461 This is equivalent to the method ``numpy.sum``. 

9462 

9463 Parameters 

9464 ---------- 

9465 axis : {index (0)} 

9466 Axis for the function to be applied on. 

9467 For `Series` this parameter is unused and defaults to 0. 

9468 

9469 .. warning:: 

9470 

9471 The behavior of DataFrame.sum with ``axis=None`` is deprecated, 

9472 in a future version this will reduce over both axes and return a scalar 

9473 To retain the old behavior, pass axis=0 (or do not pass axis). 

9474 

9475 .. versionadded:: 2.0.0 

9476 

9477 skipna : bool, default True 

9478 Exclude NA/null values when computing the result. 

9479 numeric_only : bool, default False 

9480 Include only float, int, boolean columns. Not implemented for Series. 

9481 

9482 min_count : int, default 0 

9483 The required number of valid values to perform the operation. If fewer than 

9484 ``min_count`` non-NA values are present the result will be NA. 

9485 **kwargs 

9486 Additional keyword arguments have no effect but might be accepted for 

9487 compatibility with NumPy. See :ref:`gotchas.numpy_kwargs` for more. 

9488 

9489 Returns 

9490 ------- 

9491 scalar 

9492 Sum of the values for the requested axis. 

9493 

9494 See Also 

9495 -------- 

9496 numpy.sum : Equivalent numpy function for computing sum. 

9497 Series.mean : Mean of the values. 

9498 Series.median : Median of the values. 

9499 Series.std : Standard deviation of the values. 

9500 Series.var : Variance of the values. 

9501 Series.min : Minimum value. 

9502 Series.max : Maximum value. 

9503 

9504 Examples 

9505 -------- 

9506 >>> idx = pd.MultiIndex.from_arrays( 

9507 ... [["warm", "warm", "cold", "cold"], ["dog", "falcon", "fish", "spider"]], 

9508 ... names=["blooded", "animal"], 

9509 ... ) 

9510 >>> s = pd.Series([4, 2, 0, 8], name="legs", index=idx) 

9511 >>> s 

9512 blooded animal 

9513 warm dog 4 

9514 falcon 2 

9515 cold fish 0 

9516 spider 8 

9517 Name: legs, dtype: int64 

9518 

9519 >>> s.sum() 

9520 14 

9521 

9522 By default, the sum of an empty or all-NA Series is ``0``. 

9523 

9524 >>> pd.Series([], dtype="float64").sum() # min_count=0 is the default 

9525 0.0 

9526 

9527 This can be controlled with the ``min_count`` parameter. For example, if 

9528 you'd like the sum of an empty series to be NaN, pass ``min_count=1``. 

9529 

9530 >>> pd.Series([], dtype="float64").sum(min_count=1) 

9531 nan 

9532 

9533 Thanks to the ``skipna`` parameter, ``min_count`` handles all-NA and 

9534 empty series identically. 

9535 

9536 >>> pd.Series([np.nan]).sum() 

9537 0.0 

9538 

9539 >>> pd.Series([np.nan]).sum(min_count=1) 

9540 nan 

9541 """ 

9542 return NDFrame.sum( 

9543 self, 

9544 axis=axis, 

9545 skipna=skipna, 

9546 numeric_only=numeric_only, 

9547 min_count=min_count, 

9548 **kwargs, 

9549 ) 

9550 

9551 @deprecate_nonkeyword_arguments(Pandas4Warning, allowed_args=["self"], name="prod") 

9552 def prod( 

9553 self, 

9554 axis: Axis | None = None, 

9555 skipna: bool = True, 

9556 numeric_only: bool = False, 

9557 min_count: int = 0, 

9558 **kwargs, 

9559 ): 

9560 """ 

9561 Return the product of the values over the requested axis. 

9562 

9563 By default, missing values are skipped. To include them in the calculation, 

9564 set ``skipna`` parameter to False. 

9565 

9566 Parameters 

9567 ---------- 

9568 axis : {index (0)} 

9569 Axis for the function to be applied on. 

9570 For `Series` this parameter is unused and defaults to 0. 

9571 

9572 .. warning:: 

9573 The behavior of DataFrame.prod with ``axis=None`` is deprecated, 

9574 in a future version this will reduce over both axes and return a scalar 

9575 To retain the old behavior, pass axis=0 (or do not pass axis). 

9576 

9577 .. versionadded:: 2.0.0 

9578 skipna : bool, default True 

9579 Exclude NA/null values when computing the result. 

9580 numeric_only : bool, default False 

9581 Include only float, int, boolean columns. Not implemented for Series. 

9582 min_count : int, default 0 

9583 The required number of valid values to perform the operation. If fewer than 

9584 ``min_count`` non-NA values are present the result will be NA. 

9585 **kwargs 

9586 Additional keyword arguments have no effect but might be accepted for 

9587 compatibility with NumPy. See :ref:`gotchas.numpy_kwargs` for more. 

9588 

9589 Returns 

9590 ------- 

9591 scalar 

9592 Value containing the calculation referenced in the description. 

9593 

9594 See Also 

9595 -------- 

9596 Series.sum : Return the sum. 

9597 Series.min : Return the minimum. 

9598 Series.max : Return the maximum. 

9599 Series.idxmin : Return the index of the minimum. 

9600 Series.idxmax : Return the index of the maximum. 

9601 

9602 DataFrame.sum : Return the sum over the requested axis. 

9603 DataFrame.min : Return the minimum over the requested axis. 

9604 DataFrame.max : Return the maximum over the requested axis. 

9605 DataFrame.idxmin : Return the index of the minimum over the requested axis. 

9606 DataFrame.idxmax : Return the index of the maximum over the requested axis. 

9607 

9608 Examples 

9609 -------- 

9610 By default, the product of an empty or all-NA Series is ``1`` 

9611 

9612 >>> pd.Series([], dtype="float64").prod() 

9613 1.0 

9614 

9615 This can be controlled with the ``min_count`` parameter 

9616 

9617 >>> pd.Series([], dtype="float64").prod(min_count=1) 

9618 nan 

9619 

9620 Thanks to the ``skipna`` parameter, ``min_count`` handles all-NA and 

9621 empty series identically. 

9622 

9623 >>> pd.Series([np.nan]).prod() 

9624 1.0 

9625 >>> pd.Series([np.nan]).prod(min_count=1) 

9626 nan 

9627 """ 

9628 return NDFrame.prod( 

9629 self, 

9630 axis=axis, 

9631 skipna=skipna, 

9632 numeric_only=numeric_only, 

9633 min_count=min_count, 

9634 **kwargs, 

9635 ) 

9636 

9637 @deprecate_nonkeyword_arguments(Pandas4Warning, allowed_args=["self"], name="mean") 

9638 def mean( 

9639 self, 

9640 axis: Axis | None = 0, 

9641 skipna: bool = True, 

9642 numeric_only: bool = False, 

9643 **kwargs, 

9644 ) -> Any: 

9645 """ 

9646 Return the mean of the values over the requested axis. 

9647 

9648 This method computes the arithmetic mean of the Series values, 

9649 optionally skipping missing values. 

9650 

9651 Parameters 

9652 ---------- 

9653 axis : {index (0)} 

9654 Axis for the function to be applied on. 

9655 For `Series` this parameter is unused and defaults to 0. 

9656 

9657 For DataFrames, specifying ``axis=None`` will apply the aggregation 

9658 across both axes. 

9659 

9660 .. versionadded:: 2.0.0 

9661 

9662 skipna : bool, default True 

9663 Exclude NA/null values when computing the result. 

9664 numeric_only : bool, default False 

9665 Include only float, int, boolean columns. 

9666 **kwargs 

9667 Additional keyword arguments have no effect but might be accepted for 

9668 compatibility with NumPy. See :ref:`gotchas.numpy_kwargs` for more. 

9669 

9670 Returns 

9671 ------- 

9672 scalar 

9673 Mean of the values for the requested axis. 

9674 

9675 See Also 

9676 -------- 

9677 numpy.median : Equivalent numpy function for computing median. 

9678 Series.sum : Sum of the values. 

9679 Series.median : Median of the values. 

9680 Series.std : Standard deviation of the values. 

9681 Series.var : Variance of the values. 

9682 Series.min : Minimum value. 

9683 Series.max : Maximum value. 

9684 

9685 Examples 

9686 -------- 

9687 >>> s = pd.Series([1, 2, 3]) 

9688 >>> s.mean() 

9689 2.0 

9690 """ 

9691 return NDFrame.mean( 

9692 self, axis=axis, skipna=skipna, numeric_only=numeric_only, **kwargs 

9693 ) 

9694 

9695 @deprecate_nonkeyword_arguments( 

9696 Pandas4Warning, allowed_args=["self"], name="median" 

9697 ) 

9698 def median( 

9699 self, 

9700 axis: Axis | None = 0, 

9701 skipna: bool = True, 

9702 numeric_only: bool = False, 

9703 **kwargs, 

9704 ) -> Any: 

9705 """ 

9706 Return the median of the values over the requested axis. 

9707 

9708 This method computes the median (middle value) of the Series values, 

9709 optionally skipping missing values. 

9710 

9711 Parameters 

9712 ---------- 

9713 axis : {index (0)} 

9714 Axis for the function to be applied on. 

9715 For `Series` this parameter is unused and defaults to 0. 

9716 

9717 For DataFrames, specifying ``axis=None`` will apply the aggregation 

9718 across both axes. 

9719 

9720 .. versionadded:: 2.0.0 

9721 

9722 skipna : bool, default True 

9723 Exclude NA/null values when computing the result. 

9724 numeric_only : bool, default False 

9725 Include only float, int, boolean columns. 

9726 **kwargs 

9727 Additional keyword arguments have no effect but might be accepted for 

9728 compatibility with NumPy. See :ref:`gotchas.numpy_kwargs` for more. 

9729 

9730 Returns 

9731 ------- 

9732 scalar 

9733 Median of the values for the requested axis. 

9734 

9735 See Also 

9736 -------- 

9737 numpy.median : Equivalent numpy function for computing median. 

9738 Series.sum : Sum of the values. 

9739 Series.median : Median of the values. 

9740 Series.std : Standard deviation of the values. 

9741 Series.var : Variance of the values. 

9742 Series.min : Minimum value. 

9743 Series.max : Maximum value. 

9744 

9745 Examples 

9746 -------- 

9747 >>> s = pd.Series([1, 2, 3]) 

9748 >>> s.median() 

9749 2.0 

9750 

9751 With a DataFrame 

9752 

9753 >>> df = pd.DataFrame({"a": [1, 2], "b": [2, 3]}, index=["tiger", "zebra"]) 

9754 >>> df 

9755 a b 

9756 tiger 1 2 

9757 zebra 2 3 

9758 >>> df.median() 

9759 a 1.5 

9760 b 2.5 

9761 dtype: float64 

9762 

9763 Using axis=1 

9764 

9765 >>> df.median(axis=1) 

9766 tiger 1.5 

9767 zebra 2.5 

9768 dtype: float64 

9769 

9770 In this case, `numeric_only` should be set to `True` 

9771 to avoid getting an error. 

9772 

9773 >>> df = pd.DataFrame({"a": [1, 2], "b": ["T", "Z"]}, index=["tiger", "zebra"]) 

9774 >>> df.median(numeric_only=True) 

9775 a 1.5 

9776 dtype: float64 

9777 """ 

9778 return NDFrame.median( 

9779 self, axis=axis, skipna=skipna, numeric_only=numeric_only, **kwargs 

9780 ) 

9781 

9782 @deprecate_nonkeyword_arguments(Pandas4Warning, allowed_args=["self"], name="sem") 

9783 def sem( 

9784 self, 

9785 axis: Axis | None = None, 

9786 skipna: bool = True, 

9787 ddof: int = 1, 

9788 numeric_only: bool = False, 

9789 **kwargs, 

9790 ): 

9791 """ 

9792 Return unbiased standard error of the mean over requested axis. 

9793 

9794 Normalized by N-1 by default. This can be changed using the ddof argument 

9795 

9796 Parameters 

9797 ---------- 

9798 axis : {index (0)} 

9799 This parameter is unused and defaults to 0. 

9800 skipna : bool, default True 

9801 Exclude NA/null values. If an entire row/column is NA, the result 

9802 will be NA. 

9803 ddof : int, default 1 

9804 Delta Degrees of Freedom. The divisor used in calculations is N - ddof, 

9805 where N represents the number of elements. 

9806 numeric_only : bool, default False 

9807 Include only float, int, boolean columns. Not implemented for Series. 

9808 **kwargs : 

9809 Additional keywords have no effect but might be accepted 

9810 for compatibility with NumPy. See :ref:`gotchas.numpy_kwargs` for more. 

9811 

9812 Returns 

9813 ------- 

9814 scalar 

9815 Unbiased standard error of the mean over requested axis. 

9816 

9817 See Also 

9818 -------- 

9819 scipy.stats.sem : Compute standard error of the mean. 

9820 Series.std : Return sample standard deviation over requested axis. 

9821 Series.var : Return unbiased variance over requested axis. 

9822 Series.mean : Return the mean of the values over the requested axis. 

9823 Series.median : Return the median of the values over the requested axis. 

9824 Series.mode : Return the mode(s) of the Series. 

9825 

9826 Examples 

9827 -------- 

9828 >>> s = pd.Series([1, 2, 3]) 

9829 >>> round(s.sem(), 6) 

9830 0.57735 

9831 """ 

9832 return NDFrame.sem( 

9833 self, 

9834 axis=axis, 

9835 skipna=skipna, 

9836 ddof=ddof, 

9837 numeric_only=numeric_only, 

9838 **kwargs, 

9839 ) 

9840 

9841 @deprecate_nonkeyword_arguments(Pandas4Warning, allowed_args=["self"], name="var") 

9842 def var( 

9843 self, 

9844 axis: Axis | None = None, 

9845 skipna: bool = True, 

9846 ddof: int = 1, 

9847 numeric_only: bool = False, 

9848 **kwargs, 

9849 ): 

9850 """ 

9851 Return unbiased variance over requested axis. 

9852 

9853 Normalized by N-1 by default. This can be changed using the ddof argument. 

9854 

9855 Parameters 

9856 ---------- 

9857 axis : {index (0)} 

9858 For `Series` this parameter is unused and defaults to 0. 

9859 

9860 .. warning:: 

9861 

9862 The behavior of DataFrame.var with ``axis=None`` is deprecated, 

9863 in a future version this will reduce over both axes and return a scalar 

9864 To retain the old behavior, pass axis=0 (or do not pass axis). 

9865 

9866 skipna : bool, default True 

9867 Exclude NA/null values. If an entire row/column is NA, the result 

9868 will be NA. 

9869 ddof : int, default 1 

9870 Delta Degrees of Freedom. The divisor used in calculations is N - ddof, 

9871 where N represents the number of elements. 

9872 numeric_only : bool, default False 

9873 Include only float, int, boolean columns. Not implemented for Series. 

9874 **kwargs : 

9875 Additional keywords passed. 

9876 

9877 Returns 

9878 ------- 

9879 scalar 

9880 Unbiased variance over requested axis. 

9881 

9882 See Also 

9883 -------- 

9884 numpy.var : Equivalent function in NumPy. 

9885 Series.std : Returns the standard deviation of the Series. 

9886 DataFrame.var : Returns the variance of the DataFrame. 

9887 DataFrame.std : Return standard deviation of the values over 

9888 the requested axis. 

9889 

9890 Examples 

9891 -------- 

9892 >>> df = pd.DataFrame( 

9893 ... { 

9894 ... "person_id": [0, 1, 2, 3], 

9895 ... "age": [21, 25, 62, 43], 

9896 ... "height": [1.61, 1.87, 1.49, 2.01], 

9897 ... } 

9898 ... ).set_index("person_id") 

9899 >>> df 

9900 age height 

9901 person_id 

9902 0 21 1.61 

9903 1 25 1.87 

9904 2 62 1.49 

9905 3 43 2.01 

9906 

9907 >>> df.var() 

9908 age 352.916667 

9909 height 0.056367 

9910 dtype: float64 

9911 

9912 Alternatively, ``ddof=0`` can be set to normalize by N instead of N-1: 

9913 

9914 >>> df.var(ddof=0) 

9915 age 264.687500 

9916 height 0.042275 

9917 dtype: float64 

9918 """ 

9919 return NDFrame.var( 

9920 self, 

9921 axis=axis, 

9922 skipna=skipna, 

9923 ddof=ddof, 

9924 numeric_only=numeric_only, 

9925 **kwargs, 

9926 ) 

9927 

9928 @deprecate_nonkeyword_arguments(Pandas4Warning, allowed_args=["self"], name="std") 

9929 def std( 

9930 self, 

9931 axis: Axis | None = None, 

9932 skipna: bool = True, 

9933 ddof: int = 1, 

9934 numeric_only: bool = False, 

9935 **kwargs, 

9936 ): 

9937 """ 

9938 Return sample standard deviation. 

9939 

9940 Normalized by N-1 by default. This can be changed using the ddof argument. 

9941 

9942 Parameters 

9943 ---------- 

9944 axis : {index (0)} 

9945 This parameter is unused and defaults to 0. 

9946 skipna : bool, default True 

9947 Exclude NA/null values. If Series is NA, the result 

9948 will be NA. 

9949 ddof : int, default 1 

9950 Delta Degrees of Freedom. The divisor used in calculations is N - ddof, 

9951 where N represents the number of elements. 

9952 numeric_only : bool, default False 

9953 Not implemented for Series. 

9954 **kwargs : 

9955 Additional keywords have no effect but might be accepted 

9956 for compatibility with NumPy. See :ref:`gotchas.numpy_kwargs` for more. 

9957 

9958 Returns 

9959 ------- 

9960 scalar 

9961 Standard deviation over all values in the Series. 

9962 

9963 See Also 

9964 -------- 

9965 numpy.std : Compute the standard deviation along the specified axis. 

9966 Series.var : Return unbiased variance over requested axis. 

9967 Series.sem : Return unbiased standard error of the mean over requested axis. 

9968 Series.mean : Return the mean of the values over the requested axis. 

9969 Series.median : Return the median of the values over the requested axis. 

9970 Series.mode : Return the mode(s) of the Series. 

9971 

9972 Notes 

9973 ----- 

9974 To have the same behaviour as ``numpy.std``, use ``ddof=0`` (instead of 

9975 the default ``ddof=1``) and ``skipna=False``. 

9976 

9977 Examples 

9978 -------- 

9979 >>> s = pd.Series([1, 2, 3]) 

9980 >>> s.std() 

9981 1.0 

9982 

9983 Alternatively, ``ddof=0`` can be set to normalize by $N$ instead of $N-1$: 

9984 

9985 >>> s.std(ddof=0) 

9986 0.816496580927726 

9987 """ 

9988 return NDFrame.std( 

9989 self, 

9990 axis=axis, 

9991 skipna=skipna, 

9992 ddof=ddof, 

9993 numeric_only=numeric_only, 

9994 **kwargs, 

9995 ) 

9996 

9997 @deprecate_nonkeyword_arguments(Pandas4Warning, allowed_args=["self"], name="skew") 

9998 def skew( 

9999 self, 

10000 axis: Axis | None = 0, 

10001 skipna: bool = True, 

10002 numeric_only: bool = False, 

10003 **kwargs, 

10004 ): 

10005 """ 

10006 Return unbiased skew over requested axis. 

10007 

10008 Normalized by N-1. 

10009 

10010 Parameters 

10011 ---------- 

10012 axis : {index (0)} 

10013 This parameter is unused and defaults to 0. 

10014 skipna : bool, default True 

10015 Exclude NA/null values when computing the result. 

10016 numeric_only : bool, default False 

10017 Unused. 

10018 **kwargs 

10019 Additional keyword arguments have no effect but might be accepted for 

10020 compatibility with NumPy. See :ref:`gotchas.numpy_kwargs` for more. 

10021 

10022 Returns 

10023 ------- 

10024 scalar 

10025 Unbiased skew of the Series. 

10026 

10027 See Also 

10028 -------- 

10029 

10030 Series.var : Return unbiased variance over requested axis. 

10031 Series.std : Return unbiased standard deviation over requested axis. 

10032 

10033 Examples 

10034 -------- 

10035 >>> s = pd.Series([1, 2, 3]) 

10036 >>> s.skew() 

10037 0.0 

10038 """ 

10039 return NDFrame.skew( 

10040 self, axis=axis, skipna=skipna, numeric_only=numeric_only, **kwargs 

10041 ) 

10042 

10043 @deprecate_nonkeyword_arguments(Pandas4Warning, allowed_args=["self"], name="kurt") 

10044 def kurt( 

10045 self, 

10046 axis: Axis | None = 0, 

10047 skipna: bool = True, 

10048 numeric_only: bool = False, 

10049 **kwargs, 

10050 ): 

10051 """ 

10052 Return unbiased kurtosis over requested axis. 

10053 

10054 Kurtosis obtained using Fisher's definition of 

10055 kurtosis (kurtosis of normal == 0.0). Normalized by N-1. 

10056 

10057 Parameters 

10058 ---------- 

10059 axis : {index (0)} 

10060 Axis for the function to be applied on. 

10061 For `Series` this parameter is unused and defaults to 0. 

10062 

10063 For DataFrames, specifying ``axis=None`` will apply the aggregation 

10064 across both axes. 

10065 

10066 .. versionadded:: 2.0.0 

10067 

10068 skipna : bool, default True 

10069 Exclude NA/null values when computing the result. 

10070 numeric_only : bool, default False 

10071 Include only float, int, boolean columns. 

10072 

10073 **kwargs 

10074 Additional keyword arguments have no effect but might be accepted for 

10075 compatibility with NumPy. See :ref:`gotchas.numpy_kwargs` for more. 

10076 

10077 Returns 

10078 ------- 

10079 scalar 

10080 Unbiased kurtosis. 

10081 

10082 See Also 

10083 -------- 

10084 Series.skew : Return unbiased skew over requested axis. 

10085 Series.var : Return unbiased variance over requested axis. 

10086 Series.std : Return unbiased standard deviation over requested axis. 

10087 

10088 Examples 

10089 -------- 

10090 >>> s = pd.Series([1, 2, 2, 3], index=["cat", "dog", "dog", "mouse"]) 

10091 >>> s 

10092 cat 1 

10093 dog 2 

10094 dog 2 

10095 mouse 3 

10096 dtype: int64 

10097 >>> round(s.kurt(), 6) 

10098 1.5 

10099 """ 

10100 return NDFrame.kurt( 

10101 self, axis=axis, skipna=skipna, numeric_only=numeric_only, **kwargs 

10102 ) 

10103 

10104 kurtosis = kurt 

10105 product = prod 

10106 

10107 def cummin(self, axis: Axis = 0, skipna: bool = True, *args, **kwargs) -> Self: 

10108 """ 

10109 Return cumulative minimum over a Series. 

10110 

10111 Returns a Series of the same size containing the cumulative 

10112 minimum. 

10113 

10114 Parameters 

10115 ---------- 

10116 axis : {0 or 'index'}, default 0 

10117 This parameter is unused and defaults to 0. 

10118 skipna : bool, default True 

10119 If the entire series is NA, the result will be NA. 

10120 *args, **kwargs 

10121 Additional keywords have no effect but might be accepted for 

10122 compatibility with NumPy. See :ref:`gotchas.numpy_kwargs` for more. 

10123 

10124 Returns 

10125 ------- 

10126 Series 

10127 Return cumulative minimum of the Series. 

10128 

10129 See Also 

10130 -------- 

10131 core.window.expanding.Expanding.min : Similar functionality 

10132 but ignores ``NaN`` values. 

10133 Series.min : Return the minimum value of the Series. 

10134 Series.cummax : Return cumulative maximum. 

10135 Series.cumsum : Return cumulative sum. 

10136 Series.cumprod : Return cumulative product. 

10137 

10138 Examples 

10139 -------- 

10140 >>> s = pd.Series([2, np.nan, 5, -1, 0]) 

10141 >>> s 

10142 0 2.0 

10143 1 NaN 

10144 2 5.0 

10145 3 -1.0 

10146 4 0.0 

10147 dtype: float64 

10148 

10149 By default, NA values are ignored. 

10150 

10151 >>> s.cummin() 

10152 0 2.0 

10153 1 NaN 

10154 2 2.0 

10155 3 -1.0 

10156 4 -1.0 

10157 dtype: float64 

10158 

10159 To include NA values in the operation, use ``skipna=False`` 

10160 

10161 >>> s.cummin(skipna=False) 

10162 0 2.0 

10163 1 NaN 

10164 2 NaN 

10165 3 NaN 

10166 4 NaN 

10167 dtype: float64 

10168 """ 

10169 return NDFrame.cummin(self, axis, skipna, *args, **kwargs) 

10170 

10171 def cummax(self, axis: Axis = 0, skipna: bool = True, *args, **kwargs) -> Self: 

10172 """ 

10173 Return cumulative maximum over a Series. 

10174 

10175 Returns a Series of the same size containing the cumulative 

10176 maximum. 

10177 

10178 Parameters 

10179 ---------- 

10180 axis : {0 or 'index'}, default 0 

10181 This parameter is unused and defaults to 0. 

10182 skipna : bool, default True 

10183 Exclude NA/null values. If the series is NA, the result is NA. 

10184 *args, **kwargs 

10185 Additional keywords have no effect but might be accepted for 

10186 compatibility with NumPy. See :ref:`gotchas.numpy_kwargs` for more. 

10187 

10188 Returns 

10189 ------- 

10190 Series 

10191 Return cumulative maximum of Series. 

10192 

10193 See Also 

10194 -------- 

10195 core.window.expanding.Expanding.max : Similar functionality 

10196 but ignores ``NaN`` values. 

10197 Series.max : Return the maximum over a Series. 

10198 Series.cummin : Return cumulative minimum. 

10199 Series.cumsum : Return cumulative sum. 

10200 Series.cumprod : Return cumulative product. 

10201 

10202 Examples 

10203 -------- 

10204 >>> s = pd.Series([2, np.nan, 5, -1, 0]) 

10205 >>> s 

10206 0 2.0 

10207 1 NaN 

10208 2 5.0 

10209 3 -1.0 

10210 4 0.0 

10211 dtype: float64 

10212 

10213 By default, NA values are ignored. 

10214 

10215 >>> s.cummax() 

10216 0 2.0 

10217 1 NaN 

10218 2 5.0 

10219 3 5.0 

10220 4 5.0 

10221 dtype: float64 

10222 

10223 To include NA values in the operation, use ``skipna=False`` 

10224 

10225 >>> s.cummax(skipna=False) 

10226 0 2.0 

10227 1 NaN 

10228 2 NaN 

10229 3 NaN 

10230 4 NaN 

10231 dtype: float64 

10232 """ 

10233 return NDFrame.cummax(self, axis, skipna, *args, **kwargs) 

10234 

10235 def cumsum(self, axis: Axis = 0, skipna: bool = True, *args, **kwargs) -> Self: 

10236 """ 

10237 Return cumulative sum over a Series. 

10238 

10239 Returns a Series of the same size containing the cumulative sum. 

10240 

10241 Parameters 

10242 ---------- 

10243 axis : {0 or 'index'}, default 0 

10244 This parameter is unused and defaults to 0. 

10245 skipna : bool, default True 

10246 Exclude NA/null values. If entire series is NA, the result will be NA. 

10247 *args, **kwargs 

10248 Additional keywords have no effect but might be accepted for 

10249 compatibility with NumPy. See :ref:`gotchas.numpy_kwargs` for more. 

10250 

10251 Returns 

10252 ------- 

10253 Series 

10254 Return cumulative sum of Series. 

10255 

10256 See Also 

10257 -------- 

10258 core.window.expanding.Expanding.sum : Similar functionality 

10259 but ignores ``NaN`` values. 

10260 Series.sum : Return the sum over Series. 

10261 Series.cummax : Return cumulative maximum. 

10262 Series.cummin : Return cumulative minimum. 

10263 Series.cumprod : Return cumulative product. 

10264 

10265 Examples 

10266 -------- 

10267 >>> s = pd.Series([2, np.nan, 5, -1, 0]) 

10268 >>> s 

10269 0 2.0 

10270 1 NaN 

10271 2 5.0 

10272 3 -1.0 

10273 4 0.0 

10274 dtype: float64 

10275 

10276 By default, NA values are ignored. 

10277 

10278 >>> s.cumsum() 

10279 0 2.0 

10280 1 NaN 

10281 2 7.0 

10282 3 6.0 

10283 4 6.0 

10284 dtype: float64 

10285 

10286 To include NA values in the operation, use ``skipna=False`` 

10287 

10288 >>> s.cumsum(skipna=False) 

10289 0 2.0 

10290 1 NaN 

10291 2 NaN 

10292 3 NaN 

10293 4 NaN 

10294 dtype: float64 

10295 """ 

10296 return NDFrame.cumsum(self, axis, skipna, *args, **kwargs) 

10297 

10298 def cumprod(self, axis: Axis = 0, skipna: bool = True, *args, **kwargs) -> Self: 

10299 """ 

10300 Return cumulative product over a Series. 

10301 

10302 Returns a Series of the same size containing the cumulative 

10303 product. 

10304 

10305 Parameters 

10306 ---------- 

10307 axis : {0 or 'index'}, default 0 

10308 This parameter is unused and defaults to 0. 

10309 skipna : bool, default True 

10310 Exclude NA/null values. If entire Series is NA, the result will be NA. 

10311 *args, **kwargs 

10312 Additional keywords have no effect but might be accepted for 

10313 compatibility with NumPy. See :ref:`gotchas.numpy_kwargs` for more. 

10314 

10315 Returns 

10316 ------- 

10317 Series 

10318 Return cumulative product of Series. 

10319 

10320 See Also 

10321 -------- 

10322 Series.prod : Return the product over Series. 

10323 Series.cummax : Return cumulative maximum. 

10324 Series.cummin : Return cumulative minimum. 

10325 Series.cumsum : Return cumulative sum. 

10326 

10327 Examples 

10328 -------- 

10329 >>> s = pd.Series([2, np.nan, 5, -1, 0]) 

10330 >>> s 

10331 0 2.0 

10332 1 NaN 

10333 2 5.0 

10334 3 -1.0 

10335 4 0.0 

10336 dtype: float64 

10337 

10338 By default, NA values are ignored. 

10339 

10340 >>> s.cumprod() 

10341 0 2.0 

10342 1 NaN 

10343 2 10.0 

10344 3 -10.0 

10345 4 -0.0 

10346 dtype: float64 

10347 

10348 To include NA values in the operation, use ``skipna=False`` 

10349 

10350 >>> s.cumprod(skipna=False) 

10351 0 2.0 

10352 1 NaN 

10353 2 NaN 

10354 3 NaN 

10355 4 NaN 

10356 dtype: float64 

10357 """ 

10358 return NDFrame.cumprod(self, axis, skipna, *args, **kwargs)