Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/pandas/core/generic.py: 22%
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
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
1# pyright: reportPropertyTypeMismatch=false
2from __future__ import annotations
4import collections
5from copy import deepcopy
6import datetime as dt
7from functools import partial
8from json import loads
9import operator
10import pickle
11import re
12import sys
13from typing import (
14 TYPE_CHECKING,
15 Any,
16 ClassVar,
17 Concatenate,
18 Literal,
19 NoReturn,
20 Self,
21 cast,
22 final,
23 overload,
24)
25import warnings
27import numpy as np
29import pandas._config.config as cf
30from pandas._config.config import _global_config as config
32from pandas._libs import lib
33from pandas._libs.lib import is_range_indexer
34from pandas._libs.tslibs import (
35 Period,
36 Timestamp,
37 to_offset,
38)
39from pandas.compat import CHAINED_WARNING_DISABLED
40from pandas.compat._constants import (
41 REF_COUNT_METHOD,
42)
43from pandas.compat._optional import import_optional_dependency
44from pandas.compat.numpy import function as nv
45from pandas.errors import (
46 AbstractMethodError,
47 ChainedAssignmentError,
48 InvalidIndexError,
49 Pandas4Warning,
50)
51from pandas.errors.cow import _chained_assignment_method_msg
52from pandas.util._decorators import deprecate_kwarg
53from pandas.util._exceptions import (
54 find_stack_level,
55 rewrite_warning,
56)
57from pandas.util._validators import (
58 check_dtype_backend,
59 validate_ascending,
60 validate_bool_kwarg,
61 validate_inclusive,
62)
64from pandas.core.dtypes.astype import astype_is_view
65from pandas.core.dtypes.cast import can_hold_element
66from pandas.core.dtypes.common import (
67 ensure_object,
68 ensure_platform_int,
69 ensure_str,
70 is_bool,
71 is_bool_dtype,
72 is_dict_like,
73 is_extension_array_dtype,
74 is_list_like,
75 is_number,
76 is_numeric_dtype,
77 is_re_compilable,
78 is_scalar,
79 pandas_dtype,
80)
81from pandas.core.dtypes.dtypes import (
82 DatetimeTZDtype,
83 ExtensionDtype,
84 PeriodDtype,
85)
86from pandas.core.dtypes.generic import (
87 ABCDataFrame,
88 ABCSeries,
89)
90from pandas.core.dtypes.inference import (
91 is_hashable,
92 is_nested_list_like,
93)
94from pandas.core.dtypes.missing import (
95 isna,
96 notna,
97)
99from pandas.core import (
100 algorithms as algos,
101 arraylike,
102 common,
103 indexing,
104 missing,
105 nanops,
106 sample,
107)
108from pandas.core.array_algos.replace import should_use_regex
109from pandas.core.arrays import ExtensionArray
110from pandas.core.base import PandasObject
111from pandas.core.col import Expression
112from pandas.core.construction import extract_array
113from pandas.core.flags import Flags
114from pandas.core.indexes.api import (
115 DatetimeIndex,
116 Index,
117 MultiIndex,
118 PeriodIndex,
119 default_index,
120 ensure_index,
121)
122from pandas.core.internals import BlockManager
123from pandas.core.methods.describe import describe_ndframe
124from pandas.core.methods.filter import (
125 filter_mask,
126 is_mask,
127)
128from pandas.core.missing import (
129 clean_fill_method,
130 clean_reindex_fill_method,
131 find_valid_index,
132)
133from pandas.core.reshape.concat import concat
134from pandas.core.sorting import get_indexer_indexer
135from pandas.core.window import (
136 Expanding,
137 ExponentialMovingWindow,
138 Rolling,
139 Window,
140)
142from pandas.io.formats.format import (
143 DataFrameFormatter,
144 DataFrameRenderer,
145)
146from pandas.io.formats.printing import pprint_thing
148if TYPE_CHECKING:
149 from collections.abc import (
150 Callable,
151 Hashable,
152 Iterator,
153 Mapping,
154 Sequence,
155 )
157 from pandas._libs.tslibs import BaseOffset
158 from pandas._typing import (
159 AlignJoin,
160 AnyArrayLike,
161 ArrayLike,
162 Axes,
163 Axis,
164 AxisInt,
165 CompressionOptions,
166 DtypeArg,
167 DtypeBackend,
168 DtypeObj,
169 FilePath,
170 FillnaOptions,
171 FloatFormatType,
172 FormattersType,
173 Frequency,
174 IgnoreRaise,
175 IndexKeyFunc,
176 IndexLabel,
177 InterpolateOptions,
178 IntervalClosedType,
179 JSONSerializable,
180 Level,
181 ListLike,
182 Manager,
183 NaPosition,
184 NDFrameT,
185 OpenFileErrors,
186 P,
187 RandomState,
188 RankMethod,
189 RankNaOption,
190 ReindexMethod,
191 Renamer,
192 Scalar,
193 SequenceNotStr,
194 SortKind,
195 StorageOptions,
196 Suffixes,
197 T,
198 TimeAmbiguous,
199 TimedeltaConvertibleTypes,
200 TimeNonexistent,
201 TimestampConvertibleTypes,
202 TimeUnit,
203 ToTimestampHow,
204 ValueKeyFunc,
205 WriteBuffer,
206 WriteExcelBuffer,
207 npt,
208 )
210 from pandas import (
211 DataFrame,
212 ExcelWriter,
213 HDFStore,
214 Series,
215 )
216 from pandas.core.indexers.objects import BaseIndexer
217 from pandas.core.resample import Resampler
220def _is_np_bool_backed(obj: NDFrame) -> bool:
221 """
222 Is obj backed entirely by numpy bool arrays?
224 Such an object needs neither filling nor casting to be used as a `where`
225 condition, so we can skip that machinery altogether (GH#51547).
226 """
227 if isinstance(obj, ABCDataFrame):
228 dtypes: list[DtypeObj] = obj._blk_dtypes
229 else:
230 dtypes = [obj.dtype]
231 return all(lib.is_np_dtype(dtype, "b") for dtype in dtypes)
234class NDFrame(PandasObject, indexing.IndexingMixin):
235 """
236 N-dimensional analogue of DataFrame. Store multi-dimensional in a
237 size-mutable, labeled data structure
239 Parameters
240 ----------
241 data : BlockManager
242 axes : list
243 copy : bool, default False
244 """
246 _internal_names: list[str] = [
247 "_mgr",
248 "_cache",
249 "_name",
250 "_metadata",
251 "_flags",
252 ]
253 _internal_names_set: set[str] = set(_internal_names)
254 _accessors: set[str] = set()
255 _hidden_attrs: frozenset[str] = frozenset([])
256 _metadata: list[str] = []
257 _mgr: Manager
258 _attrs: dict[Hashable, Any]
259 _typ: str
261 # ----------------------------------------------------------------------
262 # Constructors
264 def __init__(self, data: Manager) -> None:
265 object.__setattr__(self, "_mgr", data)
266 object.__setattr__(self, "_attrs", {})
267 object.__setattr__(self, "_flags", Flags(self, allows_duplicate_labels=True))
269 @final
270 @classmethod
271 def _init_mgr(
272 cls,
273 mgr: Manager,
274 axes: dict[Literal["index", "columns"], Axes | None],
275 dtype: DtypeObj | None = None,
276 copy: bool = False,
277 ) -> Manager:
278 """passed a manager and a axes dict"""
279 for a, axe in axes.items():
280 if axe is not None:
281 axe = ensure_index(axe)
282 bm_axis = cls._get_block_manager_axis(a)
283 mgr = mgr.reindex_axis(axe, axis=bm_axis)
285 # make a copy if explicitly requested
286 if copy:
287 mgr = mgr.copy(deep=True)
288 if dtype is not None:
289 # avoid further copies if we can
290 if (
291 isinstance(mgr, BlockManager)
292 and len(mgr.blocks) == 1
293 and mgr.blocks[0].values.dtype == dtype
294 ):
295 pass
296 else:
297 mgr = mgr.astype(dtype=dtype)
298 return mgr
300 @final
301 @classmethod
302 def _from_mgr(cls, mgr: Manager, axes: list[Index]) -> Self:
303 """
304 Construct a new object of this type from a Manager object and axes.
306 Parameters
307 ----------
308 mgr : Manager
309 Must have the same ndim as cls.
310 axes : list[Index]
312 Notes
313 -----
314 The axes must match mgr.axes, but are required for future-proofing
315 in the event that axes are refactored out of the Manager objects.
316 """
317 obj = cls.__new__(cls)
318 NDFrame.__init__(obj, mgr)
319 return obj
321 # ----------------------------------------------------------------------
322 # attrs and flags
324 @property
325 def attrs(self) -> dict[Hashable, Any]:
326 """
327 Dictionary of global attributes of this dataset.
329 .. warning::
331 attrs is experimental and may change without warning.
333 See Also
334 --------
335 DataFrame.flags : Global flags applying to this object.
337 Notes
338 -----
339 Many operations that create new datasets will copy ``attrs``. Copies
340 are always deep so that changing ``attrs`` will only affect the
341 present dataset. :func:`pandas.concat` and :func:`pandas.merge` will
342 only copy ``attrs`` if all input datasets have the same ``attrs``.
344 ``attrs`` is a property of a :class:`Series` or :class:`DataFrame` as a
345 whole, not of an individual column. The :class:`DataFrame` constructor
346 does not extract ``attrs`` from a :class:`Series` it is built from, and
347 assigning a :class:`Series` as a column of an existing
348 :class:`DataFrame` (e.g. ``df[col] = ser``) does not modify
349 :attr:`DataFrame.attrs`. Methods that build a new :class:`DataFrame`
350 from a single :class:`Series` (such as :meth:`Series.to_frame`) do
351 propagate the source ``attrs``.
353 Examples
354 --------
355 For Series:
357 >>> ser = pd.Series([1, 2, 3])
358 >>> ser.attrs = {"A": [10, 20, 30]}
359 >>> ser.attrs
360 {'A': [10, 20, 30]}
362 For DataFrame:
364 >>> df = pd.DataFrame({"A": [1, 2], "B": [3, 4]})
365 >>> df.attrs = {"A": [10, 20, 30]}
366 >>> df.attrs
367 {'A': [10, 20, 30]}
368 """
369 return self._attrs
371 @attrs.setter
372 def attrs(self, value: Mapping[Hashable, Any]) -> None:
373 self._attrs = dict(value)
375 @final
376 @property
377 def flags(self) -> Flags:
378 """
379 Get the properties associated with this pandas object.
381 The available flags are
383 * :attr:`Flags.allows_duplicate_labels`
385 See Also
386 --------
387 Flags : Flags that apply to pandas objects.
388 DataFrame.attrs : Global metadata applying to this dataset.
390 Notes
391 -----
392 "Flags" differ from "metadata". Flags reflect properties of the
393 pandas object (the Series or DataFrame). Metadata refer to properties
394 of the dataset, and should be stored in :attr:`DataFrame.attrs`.
396 Examples
397 --------
398 >>> df = pd.DataFrame({"A": [1, 2]})
399 >>> df.flags
400 <Flags(allows_duplicate_labels=True)>
402 Flags can be get or set using ``.``
404 >>> df.flags.allows_duplicate_labels
405 True
406 >>> df.flags.allows_duplicate_labels = False
408 Or by slicing with a key
410 >>> df.flags["allows_duplicate_labels"]
411 False
412 >>> df.flags["allows_duplicate_labels"] = True
413 """
414 return self._flags
416 @final
417 def set_flags(
418 self,
419 *,
420 copy: bool | lib.NoDefault = lib.no_default,
421 allows_duplicate_labels: bool | None = None,
422 ) -> Self:
423 """
424 Return a new object with updated flags.
426 This method creates a shallow copy of the original object, preserving its
427 underlying data while modifying its global flags. In particular, it allows
428 you to update properties such as whether duplicate labels are permitted. This
429 behavior is especially useful in method chains, where one wishes to
430 adjust DataFrame or Series characteristics without altering the original object.
432 Parameters
433 ----------
434 copy : bool, default False
435 This keyword is now ignored; changing its value will have no
436 impact on the method.
438 .. deprecated:: 3.0.0
440 This keyword is ignored and will be removed in pandas 4.0. Since
441 pandas 3.0, this method always returns a new object using a lazy
442 copy mechanism that defers copies until necessary
443 (Copy-on-Write). See the `user guide on Copy-on-Write
444 <https://pandas.pydata.org/docs/dev/user_guide/migration.html>`__
445 for more details.
447 allows_duplicate_labels : bool, optional
448 Whether the returned object allows duplicate labels.
450 Returns
451 -------
452 Series or DataFrame
453 The same type as the caller.
455 See Also
456 --------
457 DataFrame.attrs : Global metadata applying to this dataset.
458 DataFrame.flags : Global flags applying to this object.
460 Notes
461 -----
462 This method returns a new object that's a view on the same data
463 as the input. Mutating the input or the output values will be reflected
464 in the other.
466 This method is intended to be used in method chains.
468 "Flags" differ from "metadata". Flags reflect properties of the
469 pandas object (the Series or DataFrame). Metadata refer to properties
470 of the dataset, and should be stored in :attr:`DataFrame.attrs`.
472 Examples
473 --------
474 >>> df = pd.DataFrame({"A": [1, 2]})
475 >>> df.flags.allows_duplicate_labels
476 True
477 >>> df2 = df.set_flags(allows_duplicate_labels=False)
478 >>> df2.flags.allows_duplicate_labels
479 False
480 """
481 self._check_copy_deprecation(copy)
482 df = self.copy(deep=False)
483 if allows_duplicate_labels is not None:
484 df.flags["allows_duplicate_labels"] = allows_duplicate_labels
485 return df
487 @final
488 @classmethod
489 def _validate_dtype(cls, dtype) -> DtypeObj | None:
490 """validate the passed dtype"""
491 if dtype is not None:
492 dtype = pandas_dtype(dtype)
494 # a compound dtype
495 if dtype.kind == "V" and not isinstance(dtype, ExtensionDtype):
496 raise NotImplementedError(
497 "compound dtypes are not implemented "
498 f"in the {cls.__name__} constructor"
499 )
501 return dtype
503 # ----------------------------------------------------------------------
504 # Construction
506 # error: Signature of "_constructor" incompatible with supertype "PandasObject"
507 @property
508 def _constructor(self) -> Callable[..., Self]: # type: ignore[override]
509 """
510 Used when a manipulation result has the same dimensions as the
511 original.
512 """
513 raise AbstractMethodError(self)
515 # ----------------------------------------------------------------------
516 # Axis
517 _AXIS_ORDERS: list[Literal["index", "columns"]]
518 _AXIS_TO_AXIS_NUMBER: dict[Axis, AxisInt] = {0: 0, "index": 0, "rows": 0}
519 _info_axis_number: int
520 _info_axis_name: Literal["index", "columns"]
521 _AXIS_LEN: int
523 @final
524 def _construct_axes_dict(
525 self, axes: Sequence[Axis] | None = None, **kwargs: AxisInt
526 ) -> dict:
527 """Return an axes dictionary for myself."""
528 d = {a: self._get_axis(a) for a in (axes or self._AXIS_ORDERS)}
529 # error: Argument 1 to "update" of "MutableMapping" has incompatible type
530 # "Dict[str, Any]"; expected "SupportsKeysAndGetItem[Union[int, str], Any]"
531 d.update(kwargs) # type: ignore[arg-type]
532 return d
534 @final
535 @classmethod
536 def _get_axis_number(cls, axis: Axis) -> AxisInt:
537 try:
538 return cls._AXIS_TO_AXIS_NUMBER[axis]
539 except KeyError as err:
540 raise ValueError(
541 f"No axis named {axis} for object type {cls.__name__}"
542 ) from err
544 @final
545 @classmethod
546 def _get_axis_name(cls, axis: Axis) -> Literal["index", "columns"]:
547 axis_number = cls._get_axis_number(axis)
548 return cls._AXIS_ORDERS[axis_number]
550 @final
551 def _get_axis(self, axis: Axis) -> Index:
552 axis_number = self._get_axis_number(axis)
553 assert axis_number in {0, 1}
554 return self.index if axis_number == 0 else self.columns
556 @final
557 @classmethod
558 def _get_block_manager_axis(cls, axis: Axis) -> AxisInt:
559 """Map the axis to the block_manager axis."""
560 axis = cls._get_axis_number(axis)
561 ndim = cls._AXIS_LEN
562 if ndim == 2:
563 # i.e. DataFrame
564 return 1 - axis
565 return axis
567 @final
568 def _get_axis_resolvers(self, axis: str) -> dict[str, Series | MultiIndex]:
569 # index or columns
570 axis_index = getattr(self, axis)
571 d = {}
572 prefix = axis[0]
574 for i, name in enumerate(axis_index.names):
575 if name is not None:
576 key = level = name
577 else:
578 # prefix with 'i' or 'c' depending on the input axis
579 # e.g., you must do ilevel_0 for the 0th level of an unnamed
580 # multiiindex
581 key = f"{prefix}level_{i}"
582 level = i
584 level_values = axis_index.get_level_values(level)
585 s = level_values.to_series()
586 s.index = axis_index
587 d[key] = s
589 # put the index/columns itself in the dict
590 if isinstance(axis_index, MultiIndex):
591 dindex = axis_index
592 else:
593 dindex = axis_index.to_series()
595 d[axis] = dindex
596 return d
598 @final
599 def _get_index_resolvers(self) -> dict[Hashable, Series | MultiIndex]:
600 from pandas.core.computation.parsing import clean_column_name
602 d: dict[str, Series | MultiIndex] = {}
603 for axis_name in self._AXIS_ORDERS:
604 d.update(self._get_axis_resolvers(axis_name))
606 return {clean_column_name(k): v for k, v in d.items() if not isinstance(k, int)}
608 @final
609 def _get_cleaned_column_resolvers(self) -> dict[Hashable, Series | DataFrame]:
610 """
611 Return the special character free column resolvers of a DataFrame.
613 Column names with special characters are 'cleaned up' so that they can
614 be referred to by backtick quoting.
615 Used in :meth:`DataFrame.eval`.
616 """
617 from pandas.core.computation.parsing import clean_column_name
619 if isinstance(self, ABCSeries):
620 return {clean_column_name(self.name): self}
622 return {clean_column_name(k): self[k] for k in self.columns}
624 @final
625 @property
626 def _info_axis(self) -> Index:
627 return getattr(self, self._info_axis_name)
629 @property
630 def shape(self) -> tuple[int, ...]:
631 """
632 Return a tuple of axis dimensions
633 """
634 return tuple(len(self._get_axis(a)) for a in self._AXIS_ORDERS)
636 @property
637 def axes(self) -> list[Index]:
638 """
639 Return index label(s) of the internal NDFrame
640 """
641 # we do it this way because if we have reversed axes, then
642 # the block manager shows then reversed
643 return [self._get_axis(a) for a in self._AXIS_ORDERS]
645 @final
646 @property
647 def ndim(self) -> int:
648 """
649 Return an int representing the number of axes / array dimensions.
651 Return 1 if Series. Otherwise return 2 if DataFrame.
653 See Also
654 --------
655 numpy.ndarray.ndim : Number of array dimensions.
657 Examples
658 --------
659 >>> s = pd.Series({"a": 1, "b": 2, "c": 3})
660 >>> s.ndim
661 1
663 >>> df = pd.DataFrame({"col1": [1, 2], "col2": [3, 4]})
664 >>> df.ndim
665 2
666 """
667 return self._mgr.ndim
669 @final
670 @property
671 def size(self) -> int:
672 """
673 Return an int representing the number of elements in this object.
675 Return the number of rows if Series. Otherwise return the number of
676 rows times number of columns if DataFrame.
678 See Also
679 --------
680 numpy.ndarray.size : Number of elements in the array.
682 Examples
683 --------
684 >>> s = pd.Series({"a": 1, "b": 2, "c": 3})
685 >>> s.size
686 3
688 >>> df = pd.DataFrame({"col1": [1, 2], "col2": [3, 4]})
689 >>> df.size
690 4
691 """
693 return int(np.prod(self.shape))
695 def set_axis(
696 self,
697 labels,
698 *,
699 axis: Axis = 0,
700 copy: bool | lib.NoDefault = lib.no_default,
701 ) -> Self:
702 """
703 Assign desired index to given axis.
705 Indexes for%(extended_summary_sub)s row labels can be changed by assigning
706 a list-like or Index.
708 Parameters
709 ----------
710 labels : list-like, Index
711 The values for the new index.
713 axis : %(axes_single_arg)s, default 0
714 The axis to update. The value 0 identifies the rows. For `Series`
715 this parameter is unused and defaults to 0.
717 copy : bool, default False
718 This keyword is now ignored; changing its value will have no
719 impact on the method.
721 .. deprecated:: 3.0.0
723 This keyword is ignored and will be removed in pandas 4.0. Since
724 pandas 3.0, this method always returns a new object using a lazy
725 copy mechanism that defers copies until necessary
726 (Copy-on-Write). See the `user guide on Copy-on-Write
727 <https://pandas.pydata.org/docs/dev/user_guide/migration.html>`__
728 for more details.
730 Returns
731 -------
732 %(klass)s
733 An object of type %(klass)s.
735 See Also
736 --------
737 %(klass)s.rename_axis : Alter the name of the index%(see_also_sub)s.
738 """
739 self._check_copy_deprecation(copy)
740 return self._set_axis_nocheck(labels, axis, inplace=False)
742 @overload
743 def _set_axis_nocheck(
744 self, labels, axis: Axis, inplace: Literal[False]
745 ) -> Self: ...
747 @overload
748 def _set_axis_nocheck(self, labels, axis: Axis, inplace: Literal[True]) -> None: ...
750 @overload
751 def _set_axis_nocheck(self, labels, axis: Axis, inplace: bool) -> Self | None: ...
753 @final
754 def _set_axis_nocheck(self, labels, axis: Axis, inplace: bool) -> Self | None:
755 if inplace:
756 setattr(self, self._get_axis_name(axis), labels)
757 return None
758 obj = self.copy(deep=False)
759 setattr(obj, obj._get_axis_name(axis), labels)
760 return obj
762 @final
763 def _set_axis(self, axis: AxisInt, labels: AnyArrayLike | list) -> None:
764 """
765 This is called from the cython code when we set the `index` attribute
766 directly, e.g. `series.index = [1, 2, 3]`.
767 """
768 labels = ensure_index(labels)
769 self._mgr.set_axis(axis, labels)
771 @final
772 def droplevel(self, level: IndexLabel, axis: Axis = 0) -> Self:
773 """
774 Return Series/DataFrame with requested index / column level(s) removed.
776 This method is useful for simplifying a MultiIndex by removing one or
777 more levels.
779 Parameters
780 ----------
781 level : int, str, or list-like
782 If a string is given, must be the name of a level
783 If list-like, elements must be names or positional indexes
784 of levels.
786 axis : {0 or 'index', 1 or 'columns'}, default 0
787 Axis along which the level(s) is removed:
789 * 0 or 'index': remove level(s) in column.
790 * 1 or 'columns': remove level(s) in row.
792 For `Series` this parameter is unused and defaults to 0.
794 Returns
795 -------
796 Series/DataFrame
797 Series/DataFrame with requested index / column level(s) removed.
799 See Also
800 --------
801 DataFrame.replace : Replace values given in `to_replace` with `value`.
802 DataFrame.pivot : Return reshaped DataFrame organized by given
803 index / column values.
805 Examples
806 --------
807 >>> df = (
808 ... pd.DataFrame([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
809 ... .set_index([0, 1])
810 ... .rename_axis(["a", "b"])
811 ... )
813 >>> df.columns = pd.MultiIndex.from_tuples(
814 ... [("c", "e"), ("d", "f")], names=["level_1", "level_2"]
815 ... )
817 >>> df
818 level_1 c d
819 level_2 e f
820 a b
821 1 2 3 4
822 5 6 7 8
823 9 10 11 12
825 >>> df.droplevel("a")
826 level_1 c d
827 level_2 e f
828 b
829 2 3 4
830 6 7 8
831 10 11 12
833 >>> df.droplevel("level_2", axis=1)
834 level_1 c d
835 a b
836 1 2 3 4
837 5 6 7 8
838 9 10 11 12
839 """
840 labels = self._get_axis(axis)
841 new_labels = labels.droplevel(level)
842 return self.set_axis(new_labels, axis=axis)
844 def pop(self, item: Hashable) -> Series | Any:
845 result = self[item]
846 del self[item]
848 return result
850 @final
851 def squeeze(self, axis: Axis | None = None) -> Scalar | Series | DataFrame:
852 """
853 Squeeze 1 dimensional axis objects into scalars.
855 Series or DataFrames with a single element are squeezed to a scalar.
856 DataFrames with a single column or a single row are squeezed to a
857 Series. Otherwise the object is unchanged.
859 This method is most useful when you don't know if your
860 object is a Series or DataFrame, but you do know it has just a single
861 column. In that case you can safely call `squeeze` to ensure you have a
862 Series.
864 Parameters
865 ----------
866 axis : {0 or 'index', 1 or 'columns', None}, default None
867 A specific axis to squeeze. By default, all length-1 axes are
868 squeezed. For `Series` this parameter is unused and defaults to `None`.
870 Returns
871 -------
872 DataFrame, Series, or scalar
873 The projection after squeezing `axis` or all the axes.
875 See Also
876 --------
877 Series.iloc : Integer-location based indexing for selecting scalars.
878 DataFrame.iloc : Integer-location based indexing for selecting Series.
879 Series.to_frame : Inverse of DataFrame.squeeze for a
880 single-column DataFrame.
882 Examples
883 --------
884 >>> primes = pd.Series([2, 3, 5, 7])
886 Slicing might produce a Series with a single value:
888 >>> even_primes = primes[primes % 2 == 0]
889 >>> even_primes
890 0 2
891 dtype: int64
893 >>> even_primes.squeeze()
894 2
896 Squeezing objects with more than one value in every axis does nothing:
898 >>> odd_primes = primes[primes % 2 == 1]
899 >>> odd_primes
900 1 3
901 2 5
902 3 7
903 dtype: int64
905 >>> odd_primes.squeeze()
906 1 3
907 2 5
908 3 7
909 dtype: int64
911 Squeezing is even more effective when used with DataFrames.
913 >>> df = pd.DataFrame([[1, 2], [3, 4]], columns=["a", "b"])
914 >>> df
915 a b
916 0 1 2
917 1 3 4
919 Slicing a single column will produce a DataFrame with the columns
920 having only one value:
922 >>> df_a = df[["a"]]
923 >>> df_a
924 a
925 0 1
926 1 3
928 So the columns can be squeezed down, resulting in a Series:
930 >>> df_a.squeeze("columns")
931 0 1
932 1 3
933 Name: a, dtype: int64
935 Slicing a single row from a single column will produce a single
936 scalar DataFrame:
938 >>> df_0a = df.loc[df.index < 1, ["a"]]
939 >>> df_0a
940 a
941 0 1
943 Squeezing the rows produces a single scalar Series:
945 >>> df_0a.squeeze("rows")
946 a 1
947 Name: 0, dtype: int64
949 Squeezing all axes will project directly into a scalar:
951 >>> df_0a.squeeze()
952 1
953 """
954 axes = range(self._AXIS_LEN) if axis is None else (self._get_axis_number(axis),)
955 result = self.iloc[
956 tuple(
957 0 if i in axes and len(a) == 1 else slice(None)
958 for i, a in enumerate(self.axes)
959 )
960 ]
961 if isinstance(result, NDFrame):
962 result = result.__finalize__(self, method="squeeze")
963 return result
965 # ----------------------------------------------------------------------
966 # Rename
968 @overload
969 def _rename(
970 self,
971 mapper: Renamer | None = ...,
972 *,
973 index: Renamer | None = ...,
974 columns: Renamer | None = ...,
975 axis: Axis | None = ...,
976 inplace: Literal[False] = ...,
977 level: Level | None = ...,
978 errors: str = ...,
979 ) -> Self: ...
981 @overload
982 def _rename(
983 self,
984 mapper: Renamer | None = ...,
985 *,
986 index: Renamer | None = ...,
987 columns: Renamer | None = ...,
988 axis: Axis | None = ...,
989 inplace: Literal[True],
990 level: Level | None = ...,
991 errors: str = ...,
992 ) -> None: ...
994 @overload
995 def _rename(
996 self,
997 mapper: Renamer | None = ...,
998 *,
999 index: Renamer | None = ...,
1000 columns: Renamer | None = ...,
1001 axis: Axis | None = ...,
1002 inplace: bool,
1003 level: Level | None = ...,
1004 errors: str = ...,
1005 ) -> Self | None: ...
1007 @final
1008 def _rename(
1009 self,
1010 mapper: Renamer | None = None,
1011 *,
1012 index: Renamer | None = None,
1013 columns: Renamer | None = None,
1014 axis: Axis | None = None,
1015 inplace: bool = False,
1016 level: Level | None = None,
1017 errors: str = "ignore",
1018 ) -> Self | None:
1019 # called by Series.rename and DataFrame.rename
1021 if mapper is None and index is None and columns is None:
1022 raise TypeError("must pass an index to rename")
1024 if index is not None or columns is not None:
1025 if axis is not None:
1026 raise TypeError(
1027 "Cannot specify both 'axis' and any of 'index' or 'columns'"
1028 )
1029 if mapper is not None:
1030 raise TypeError(
1031 "Cannot specify both 'mapper' and any of 'index' or 'columns'"
1032 )
1033 # use the mapper argument
1034 elif axis and self._get_axis_number(axis) == 1:
1035 columns = mapper
1036 else:
1037 index = mapper
1039 self._check_inplace_and_allows_duplicate_labels(inplace)
1040 result = self if inplace else self.copy(deep=False)
1042 for axis_no, replacements in enumerate((index, columns)):
1043 if replacements is None:
1044 continue
1046 ax = self._get_axis(axis_no)
1047 f = common.get_rename_function(replacements)
1049 if level is not None:
1050 level = ax._get_level_number(level)
1052 if isinstance(replacements, ABCSeries) and not replacements.index.is_unique:
1053 # GH#58621
1054 raise ValueError("Cannot rename with a Series with non-unique index.")
1056 # GH 13473
1057 if not callable(replacements):
1058 if ax._is_multi and level is not None:
1059 indexer = ax.get_level_values(level).get_indexer_for(replacements) # type: ignore[arg-type]
1060 else:
1061 indexer = ax.get_indexer_for(replacements) # type: ignore[arg-type]
1063 if errors == "raise" and len(indexer[indexer == -1]):
1064 missing_labels = [
1065 label
1066 for index, label in enumerate(replacements)
1067 if indexer[index] == -1
1068 ]
1069 raise KeyError(f"{missing_labels} not found in axis")
1071 new_index = ax._transform_index(f, level=level)
1072 result._set_axis_nocheck(new_index, axis=axis_no, inplace=True)
1074 if inplace:
1075 self._update_inplace(result)
1076 return None
1077 else:
1078 return result.__finalize__(self, method="rename")
1080 @overload
1081 def rename_axis(
1082 self,
1083 mapper: IndexLabel | lib.NoDefault = ...,
1084 *,
1085 index=...,
1086 columns=...,
1087 axis: Axis = ...,
1088 copy: bool | lib.NoDefault = lib.no_default,
1089 inplace: Literal[False] = ...,
1090 ) -> Self: ...
1092 @overload
1093 def rename_axis(
1094 self,
1095 mapper: IndexLabel | lib.NoDefault = ...,
1096 *,
1097 index=...,
1098 columns=...,
1099 axis: Axis = ...,
1100 copy: bool | lib.NoDefault = lib.no_default,
1101 inplace: Literal[True],
1102 ) -> None: ...
1104 @overload
1105 def rename_axis(
1106 self,
1107 mapper: IndexLabel | lib.NoDefault = ...,
1108 *,
1109 index=...,
1110 columns=...,
1111 axis: Axis = ...,
1112 copy: bool | lib.NoDefault = lib.no_default,
1113 inplace: bool = ...,
1114 ) -> Self | None: ...
1116 def rename_axis(
1117 self,
1118 mapper: IndexLabel | lib.NoDefault = lib.no_default,
1119 *,
1120 index=lib.no_default,
1121 columns=lib.no_default,
1122 axis: Axis = 0,
1123 copy: bool | lib.NoDefault = lib.no_default,
1124 inplace: bool = False,
1125 ) -> Self | None:
1126 self._check_copy_deprecation(copy)
1127 axes = {"index": index, "columns": columns}
1129 if axis is not None:
1130 axis = self._get_axis_number(axis)
1132 inplace = validate_bool_kwarg(inplace, "inplace")
1134 if mapper is not lib.no_default:
1135 # Use v0.23 behavior if a scalar or list
1136 non_mapper = is_scalar(mapper) or (
1137 is_list_like(mapper) and not is_dict_like(mapper)
1138 )
1139 if non_mapper:
1140 return self._set_axis_name(mapper, axis=axis, inplace=inplace)
1141 else:
1142 raise ValueError("Use `.rename` to alter labels with a mapper.")
1143 else:
1144 # Use new behavior. Means that index and/or columns
1145 # is specified
1146 result = self if inplace else self.copy(deep=False)
1148 for axis in range(self._AXIS_LEN):
1149 v = axes.get(self._get_axis_name(axis))
1150 if v is lib.no_default:
1151 continue
1152 non_mapper = is_scalar(v) or (is_list_like(v) and not is_dict_like(v))
1153 if non_mapper:
1154 newnames = v
1155 else:
1156 f = common.get_rename_function(v)
1157 curnames = self._get_axis(axis).names
1158 newnames = [f(name) for name in curnames] # pyright: ignore[reportOptionalCall]
1159 result._set_axis_name(newnames, axis=axis, inplace=True)
1160 if not inplace:
1161 return result
1162 return None
1164 @overload
1165 def _set_axis_name(
1166 self, name, axis: Axis = ..., *, inplace: Literal[False] = ...
1167 ) -> Self: ...
1169 @overload
1170 def _set_axis_name(
1171 self, name, axis: Axis = ..., *, inplace: Literal[True]
1172 ) -> None: ...
1174 @overload
1175 def _set_axis_name(
1176 self, name, axis: Axis = ..., *, inplace: bool
1177 ) -> Self | None: ...
1179 @final
1180 def _set_axis_name(
1181 self, name, axis: Axis = 0, *, inplace: bool = False
1182 ) -> Self | None:
1183 """
1184 Set the name(s) of the axis.
1186 Parameters
1187 ----------
1188 name : str or list of str
1189 Name(s) to set.
1190 axis : {0 or 'index', 1 or 'columns'}, default 0
1191 The axis to set the label. The value 0 or 'index' specifies index,
1192 and the value 1 or 'columns' specifies columns.
1193 inplace : bool, default False
1194 If `True`, do operation inplace and return None.
1196 Returns
1197 -------
1198 Series, DataFrame, or None
1199 The same type as the caller or `None` if `inplace` is `True`.
1201 See Also
1202 --------
1203 DataFrame.rename : Alter the axis labels of :class:`DataFrame`.
1204 Series.rename : Alter the index labels or set the index name
1205 of :class:`Series`.
1206 Index.rename : Set the name of :class:`Index` or :class:`MultiIndex`.
1208 Examples
1209 --------
1210 >>> df = pd.DataFrame({"num_legs": [4, 4, 2]}, ["dog", "cat", "monkey"])
1211 >>> df
1212 num_legs
1213 dog 4
1214 cat 4
1215 monkey 2
1216 >>> df._set_axis_name("animal")
1217 num_legs
1218 animal
1219 dog 4
1220 cat 4
1221 monkey 2
1222 >>> df.index = pd.MultiIndex.from_product(
1223 ... [["mammal"], ["dog", "cat", "monkey"]]
1224 ... )
1225 >>> df._set_axis_name(["type", "name"])
1226 num_legs
1227 type name
1228 mammal dog 4
1229 cat 4
1230 monkey 2
1231 """
1232 axis = self._get_axis_number(axis)
1233 idx = self._get_axis(axis).set_names(name)
1235 inplace = validate_bool_kwarg(inplace, "inplace")
1236 renamed = self if inplace else self.copy(deep=False)
1237 if axis == 0:
1238 renamed.index = idx
1239 else:
1240 renamed.columns = idx
1242 if not inplace:
1243 return renamed
1244 return None
1246 # ----------------------------------------------------------------------
1247 # Comparison Methods
1249 @final
1250 def _indexed_same(self, other) -> bool:
1251 return all(
1252 self._get_axis(a).equals(other._get_axis(a)) for a in self._AXIS_ORDERS
1253 )
1255 @final
1256 def equals(self, other: object) -> bool:
1257 """
1258 Test whether two objects contain the same elements.
1260 This function allows two Series or DataFrames to be compared against
1261 each other to see if they have the same shape and elements. NaNs in
1262 the same location are considered equal.
1264 The row/column index do not need to have the same type, as long
1265 as the values are considered equal. Corresponding columns and
1266 index must be of the same dtype.
1268 Parameters
1269 ----------
1270 other : Series or DataFrame
1271 The other Series or DataFrame to be compared with the first.
1273 Returns
1274 -------
1275 bool
1276 True if all elements are the same in both objects, False
1277 otherwise.
1279 See Also
1280 --------
1281 Series.eq : Compare two Series objects of the same length
1282 and return a Series where each element is True if the element
1283 in each Series is equal, False otherwise.
1284 DataFrame.eq : Compare two DataFrame objects of the same shape and
1285 return a DataFrame where each element is True if the respective
1286 element in each DataFrame is equal, False otherwise.
1287 testing.assert_series_equal : Raises an AssertionError if left and
1288 right are not equal. Provides an easy interface to ignore
1289 inequality in dtypes, indexes and precision among others.
1290 testing.assert_frame_equal : Like assert_series_equal, but targets
1291 DataFrames.
1292 numpy.array_equal : Return True if two arrays have the same shape
1293 and elements, False otherwise.
1295 Examples
1296 --------
1297 >>> df = pd.DataFrame({1: [10], 2: [20]})
1298 >>> df
1299 1 2
1300 0 10 20
1302 DataFrames df and exactly_equal have the same types and values for
1303 their elements and column labels, which will return True.
1305 >>> exactly_equal = pd.DataFrame({1: [10], 2: [20]})
1306 >>> exactly_equal
1307 1 2
1308 0 10 20
1309 >>> df.equals(exactly_equal)
1310 True
1312 DataFrames df and different_column_type have the same element
1313 types and values, but have different types for the column labels,
1314 which will still return True.
1316 >>> different_column_type = pd.DataFrame({1.0: [10], 2.0: [20]})
1317 >>> different_column_type
1318 1.0 2.0
1319 0 10 20
1320 >>> df.equals(different_column_type)
1321 True
1323 DataFrames df and different_data_type have different types for the
1324 same values for their elements, and will return False even though
1325 their column labels are the same values and types.
1327 >>> different_data_type = pd.DataFrame({1: [10.0], 2: [20.0]})
1328 >>> different_data_type
1329 1 2
1330 0 10.0 20.0
1331 >>> df.equals(different_data_type)
1332 False
1334 DataFrames with NaN in the same locations compare equal.
1336 >>> df_nan1 = pd.DataFrame({"a": [1, np.nan], "b": [3, np.nan]})
1337 >>> df_nan2 = pd.DataFrame({"a": [1, np.nan], "b": [3, np.nan]})
1338 >>> df_nan1.equals(df_nan2)
1339 True
1341 If the NaN values are not in the same locations, they compare unequal.
1343 >>> df_nan3 = pd.DataFrame({"a": [1, np.nan], "b": [3, 4]})
1344 >>> df_nan1.equals(df_nan3)
1345 False
1346 """
1347 if not (isinstance(other, type(self)) or isinstance(self, type(other))):
1348 return False
1349 other = cast("NDFrame", other)
1350 return self._mgr.equals(other._mgr)
1352 # -------------------------------------------------------------------------
1353 # Unary Methods
1355 @final
1356 def __neg__(self) -> Self:
1357 def blk_func(values: ArrayLike):
1358 if is_bool_dtype(values.dtype):
1359 # error: Argument 1 to "inv" has incompatible type "Union
1360 # [ExtensionArray, ndarray[Any, Any]]"; expected
1361 # "_SupportsInversion[ndarray[Any, dtype[bool_]]]"
1362 return operator.inv(values) # type: ignore[arg-type]
1363 else:
1364 # error: Argument 1 to "neg" has incompatible type "Union
1365 # [ExtensionArray, ndarray[Any, Any]]"; expected
1366 # "_SupportsNeg[ndarray[Any, dtype[Any]]]"
1367 return operator.neg(values) # type: ignore[arg-type]
1369 new_data = self._mgr.apply(blk_func)
1370 res = self._constructor_from_mgr(new_data, axes=new_data.axes)
1371 return res.__finalize__(self, method="__neg__")
1373 @final
1374 def __pos__(self) -> Self:
1375 def blk_func(values: ArrayLike):
1376 if is_bool_dtype(values.dtype):
1377 return values.copy()
1378 else:
1379 # error: Argument 1 to "pos" has incompatible type "Union
1380 # [ExtensionArray, ndarray[Any, Any]]"; expected
1381 # "_SupportsPos[ndarray[Any, dtype[Any]]]"
1382 return operator.pos(values) # type: ignore[arg-type]
1384 new_data = self._mgr.apply(blk_func)
1385 res = self._constructor_from_mgr(new_data, axes=new_data.axes)
1386 return res.__finalize__(self, method="__pos__")
1388 @final
1389 def __invert__(self) -> Self:
1390 """
1391 Return the bitwise inverse of the Series/DataFrame, element-wise.
1393 Equivalent to applying the ``~`` (tilde) operator element-wise. For
1394 boolean data this returns the logical NOT; for integer data it returns
1395 the bitwise NOT (ones complement).
1397 Returns
1398 -------
1399 Series or DataFrame
1400 A new object of the same type and shape with every element
1401 bitwise inverted.
1403 See Also
1404 --------
1405 numpy.invert : Compute bitwise inversion element-wise.
1407 Examples
1408 --------
1409 **Boolean Series:**
1411 >>> s = pd.Series([True, False, True])
1412 >>> ~s
1413 0 False
1414 1 True
1415 2 False
1416 dtype: bool
1418 **Integer Series:**
1420 >>> s = pd.Series([1, 0, 3], dtype="int8")
1421 >>> ~s
1422 0 -2
1423 1 -1
1424 2 -4
1425 dtype: int8
1427 **Boolean DataFrame:**
1429 >>> df = pd.DataFrame({"a": [True, False], "b": [False, True]})
1430 >>> ~df
1431 a b
1432 0 False True
1433 1 True False
1434 """
1435 if not self.size:
1436 # inv fails with 0 len
1437 return self.copy(deep=False)
1439 new_data = self._mgr.apply(operator.invert)
1440 res = self._constructor_from_mgr(new_data, axes=new_data.axes)
1441 return res.__finalize__(self, method="__invert__")
1443 @final
1444 def __bool__(self) -> NoReturn:
1445 raise ValueError(
1446 f"The truth value of a {type(self).__name__} is ambiguous. "
1447 "Use a.empty, a.item(), a.any() or a.all()."
1448 )
1450 @final
1451 def abs(self) -> Self:
1452 """
1453 Return a Series/DataFrame with absolute numeric value of each element.
1455 This function only applies to elements that are all numeric.
1457 Returns
1458 -------
1459 abs
1460 Series/DataFrame containing the absolute value of each element.
1462 See Also
1463 --------
1464 numpy.absolute : Calculate the absolute value element-wise.
1466 Notes
1467 -----
1468 For ``complex`` inputs, ``1.2 + 1j``, the absolute value is
1469 :math:`\\sqrt{ a^2 + b^2 }`.
1471 Examples
1472 --------
1473 Absolute numeric values in a Series.
1475 >>> s = pd.Series([-1.10, 2, -3.33, 4])
1476 >>> s.abs()
1477 0 1.10
1478 1 2.00
1479 2 3.33
1480 3 4.00
1481 dtype: float64
1483 Absolute numeric values in a Series with complex numbers.
1485 >>> s = pd.Series([1.2 + 1j])
1486 >>> s.abs()
1487 0 1.56205
1488 dtype: float64
1490 Absolute numeric values in a Series with a Timedelta element.
1492 >>> s = pd.Series([pd.Timedelta("1 days")])
1493 >>> s.abs()
1494 0 1 days
1495 dtype: timedelta64[us]
1497 Select rows with data closest to certain value using argsort (from
1498 `StackOverflow <https://stackoverflow.com/a/17758115>`__).
1500 >>> df = pd.DataFrame(
1501 ... {"a": [4, 5, 6, 7], "b": [10, 20, 30, 40], "c": [100, 50, -30, -50]}
1502 ... )
1503 >>> df
1504 a b c
1505 0 4 10 100
1506 1 5 20 50
1507 2 6 30 -30
1508 3 7 40 -50
1509 >>> df.loc[(df.c - 43).abs().argsort()]
1510 a b c
1511 1 5 20 50
1512 0 4 10 100
1513 2 6 30 -30
1514 3 7 40 -50
1515 """
1516 res_mgr = self._mgr.apply(np.abs)
1517 return self._constructor_from_mgr(res_mgr, axes=res_mgr.axes).__finalize__(
1518 self, name="abs"
1519 )
1521 @final
1522 def __abs__(self) -> Self:
1523 return self.abs()
1525 @final
1526 def __round__(self, decimals: int = 0) -> Self:
1527 return self.round(decimals).__finalize__(self, method="__round__")
1529 # -------------------------------------------------------------------------
1530 # Label or Level Combination Helpers
1531 #
1532 # A collection of helper methods for DataFrame/Series operations that
1533 # accept a combination of column/index labels and levels. All such
1534 # operations should utilize/extend these methods when possible so that we
1535 # have consistent precedence and validation logic throughout the library.
1537 @final
1538 def _is_level_reference(self, key: Level, axis: Axis = 0) -> bool:
1539 """
1540 Test whether a key is a level reference for a given axis.
1542 To be considered a level reference, `key` must be a string that:
1543 - (axis=0): Matches the name of an index level and does NOT match
1544 a column label.
1545 - (axis=1): Matches the name of a column level and does NOT match
1546 an index label.
1548 Parameters
1549 ----------
1550 key : Hashable
1551 Potential level name for the given axis
1552 axis : int, default 0
1553 Axis that levels are associated with (0 for index, 1 for columns)
1555 Returns
1556 -------
1557 is_level : bool
1558 """
1559 axis_int = self._get_axis_number(axis)
1561 return (
1562 key is not None
1563 and is_hashable(key)
1564 and key in self.axes[axis_int].names
1565 and not self._is_label_reference(key, axis=axis_int)
1566 )
1568 @final
1569 def _is_label_reference(self, key: Level, axis: Axis = 0) -> bool:
1570 """
1571 Test whether a key is a label reference for a given axis.
1573 To be considered a label reference, `key` must be a string that:
1574 - (axis=0): Matches a column label
1575 - (axis=1): Matches an index label
1577 Parameters
1578 ----------
1579 key : Hashable
1580 Potential label name, i.e. Index entry.
1581 axis : int, default 0
1582 Axis perpendicular to the axis that labels are associated with
1583 (0 means search for column labels, 1 means search for index labels)
1585 Returns
1586 -------
1587 is_label: bool
1588 """
1589 axis_int = self._get_axis_number(axis)
1590 other_axes = (ax for ax in range(self._AXIS_LEN) if ax != axis_int)
1592 return is_hashable(key) and any(key in self.axes[ax] for ax in other_axes)
1594 @final
1595 def _is_label_or_level_reference(self, key: Level, axis: AxisInt = 0) -> bool:
1596 """
1597 Test whether a key is a label or level reference for a given axis.
1599 To be considered either a label or a level reference, `key` must be a
1600 string that:
1601 - (axis=0): Matches a column label or an index level
1602 - (axis=1): Matches an index label or a column level
1604 Parameters
1605 ----------
1606 key : Hashable
1607 Potential label or level name
1608 axis : int, default 0
1609 Axis that levels are associated with (0 for index, 1 for columns)
1611 Returns
1612 -------
1613 bool
1614 """
1615 return self._is_level_reference(key, axis=axis) or self._is_label_reference(
1616 key, axis=axis
1617 )
1619 @final
1620 def _check_label_or_level_ambiguity(self, key: Level, axis: Axis = 0) -> None:
1621 """
1622 Check whether `key` is ambiguous.
1624 By ambiguous, we mean that it matches both a level of the input
1625 `axis` and a label of the other axis.
1627 Parameters
1628 ----------
1629 key : Hashable
1630 Label or level name.
1631 axis : int, default 0
1632 Axis that levels are associated with (0 for index, 1 for columns).
1634 Raises
1635 ------
1636 ValueError: `key` is ambiguous
1637 """
1639 axis_int = self._get_axis_number(axis)
1640 other_axes = (ax for ax in range(self._AXIS_LEN) if ax != axis_int)
1642 if (
1643 key is not None
1644 and is_hashable(key)
1645 and key in self.axes[axis_int].names
1646 and any(key in self.axes[ax] for ax in other_axes)
1647 ):
1648 # Build an informative and grammatical warning
1649 level_article, level_type = (
1650 ("an", "index") if axis_int == 0 else ("a", "column")
1651 )
1653 label_article, label_type = (
1654 ("a", "column") if axis_int == 0 else ("an", "index")
1655 )
1657 msg = (
1658 f"'{key}' is both {level_article} {level_type} level and "
1659 f"{label_article} {label_type} label, which is ambiguous."
1660 )
1661 raise ValueError(msg)
1663 @final
1664 def _get_label_or_level_values(self, key: Level, axis: AxisInt = 0) -> ArrayLike:
1665 """
1666 Return a 1-D array of values associated with `key`, a label or level
1667 from the given `axis`.
1669 Retrieval logic:
1670 - (axis=0): Return column values if `key` matches a column label.
1671 Otherwise return index level values if `key` matches an index
1672 level.
1673 - (axis=1): Return row values if `key` matches an index label.
1674 Otherwise return column level values if 'key' matches a column
1675 level
1677 Parameters
1678 ----------
1679 key : Hashable
1680 Label or level name.
1681 axis : int, default 0
1682 Axis that levels are associated with (0 for index, 1 for columns)
1684 Returns
1685 -------
1686 np.ndarray or ExtensionArray
1688 Raises
1689 ------
1690 KeyError
1691 if `key` matches neither a label nor a level
1692 ValueError
1693 if `key` matches multiple labels
1694 """
1695 axis = self._get_axis_number(axis)
1696 first_other_axes = next(
1697 (ax for ax in range(self._AXIS_LEN) if ax != axis), None
1698 )
1700 if self._is_label_reference(key, axis=axis):
1701 self._check_label_or_level_ambiguity(key, axis=axis)
1702 if first_other_axes is None:
1703 raise ValueError("axis matched all axes")
1704 values = self.xs(key, axis=first_other_axes)._values
1705 elif self._is_level_reference(key, axis=axis):
1706 values = self.axes[axis].get_level_values(key)._values
1707 else:
1708 raise KeyError(key)
1710 # Check for duplicates
1711 if values.ndim > 1:
1712 if first_other_axes is not None and isinstance(
1713 self._get_axis(first_other_axes), MultiIndex
1714 ):
1715 multi_message = (
1716 "\n"
1717 "For a multi-index, the label must be a "
1718 "tuple with elements corresponding to each level."
1719 )
1720 else:
1721 multi_message = ""
1723 label_axis_name = "column" if axis == 0 else "index"
1724 raise ValueError(
1725 f"The {label_axis_name} label '{key}' is not unique.{multi_message}"
1726 )
1728 return values
1730 @final
1731 def _drop_labels_or_levels(self, keys, axis: AxisInt = 0):
1732 """
1733 Drop labels and/or levels for the given `axis`.
1735 For each key in `keys`:
1736 - (axis=0): If key matches a column label then drop the column.
1737 Otherwise if key matches an index level then drop the level.
1738 - (axis=1): If key matches an index label then drop the row.
1739 Otherwise if key matches a column level then drop the level.
1741 Parameters
1742 ----------
1743 keys : str or list of str
1744 labels or levels to drop
1745 axis : int, default 0
1746 Axis that levels are associated with (0 for index, 1 for columns)
1748 Returns
1749 -------
1750 dropped: DataFrame
1752 Raises
1753 ------
1754 ValueError
1755 if any `keys` match neither a label nor a level
1756 """
1757 axis = self._get_axis_number(axis)
1759 # Validate keys
1760 keys = common.maybe_make_list(keys)
1761 invalid_keys = [
1762 k
1763 for k in keys # pyright: ignore[reportOptionalIterable]
1764 if not self._is_label_or_level_reference(k, axis=axis)
1765 ]
1767 if invalid_keys:
1768 raise ValueError(
1769 "The following keys are not valid labels or "
1770 f"levels for axis {axis}: {invalid_keys}"
1771 )
1773 # Compute levels and labels to drop
1774 levels_to_drop = [
1775 k
1776 for k in keys # pyright: ignore[reportOptionalIterable]
1777 if self._is_level_reference(k, axis=axis)
1778 ]
1780 labels_to_drop = [
1781 k
1782 for k in keys # pyright: ignore[reportOptionalIterable]
1783 if not self._is_level_reference(k, axis=axis)
1784 ]
1786 # Perform copy upfront and then use inplace operations below.
1787 # This ensures that we always perform exactly one copy.
1788 # ``copy`` and/or ``inplace`` options could be added in the future.
1789 dropped = self.copy(deep=False)
1791 if axis == 0:
1792 # Handle dropping index levels
1793 if levels_to_drop:
1794 dropped = dropped.reset_index(levels_to_drop, drop=True)
1796 # Handle dropping columns labels
1797 if labels_to_drop:
1798 dropped = dropped.drop(labels_to_drop, axis=1)
1799 else:
1800 # Handle dropping column levels
1801 if levels_to_drop:
1802 if isinstance(dropped.columns, MultiIndex):
1803 # Drop the specified levels from the MultiIndex
1804 dropped.columns = dropped.columns.droplevel(levels_to_drop)
1805 else:
1806 # Drop the last level of Index by replacing with
1807 # a RangeIndex
1808 dropped.columns = default_index(dropped.columns.size)
1810 # Handle dropping index labels
1811 if labels_to_drop:
1812 dropped = dropped.drop(labels_to_drop, axis=0)
1814 return dropped
1816 # ----------------------------------------------------------------------
1817 # Iteration
1819 # https://github.com/python/typeshed/issues/2148#issuecomment-520783318
1820 # Incompatible types in assignment (expression has type "None", base class
1821 # "object" defined the type as "Callable[[object], int]")
1822 __hash__: ClassVar[None] # type: ignore[assignment]
1824 def __iter__(self) -> Iterator:
1825 """
1826 Iterate over info axis.
1828 For a DataFrame this yields column names (labels); for a Series
1829 it yields the single name. Enables iteration over the object
1830 with ``for col in df``.
1832 Returns
1833 -------
1834 iterator
1835 Info axis as iterator.
1837 See Also
1838 --------
1839 DataFrame.items : Iterate over (column name, Series) pairs.
1840 DataFrame.itertuples : Iterate over DataFrame rows as namedtuples.
1842 Examples
1843 --------
1844 >>> df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
1845 >>> for x in df:
1846 ... print(x)
1847 A
1848 B
1849 """
1850 return iter(self._info_axis)
1852 # can we get a better explanation of this?
1853 def keys(self) -> Index:
1854 """
1855 Get the 'info axis' (see Indexing for more).
1857 This is index for Series, columns for DataFrame.
1859 Returns
1860 -------
1861 Index
1862 Info axis.
1864 See Also
1865 --------
1866 DataFrame.index : The index (row labels) of the DataFrame.
1867 DataFrame.columns: The column labels of the DataFrame.
1869 Examples
1870 --------
1871 >>> d = pd.DataFrame(
1872 ... data={"A": [1, 2, 3], "B": [0, 4, 8]}, index=["a", "b", "c"]
1873 ... )
1874 >>> d
1875 A B
1876 a 1 0
1877 b 2 4
1878 c 3 8
1879 >>> d.keys()
1880 Index(['A', 'B'], dtype='str')
1881 """
1882 return self._info_axis
1884 def items(self):
1885 """
1886 Iterate over (label, values) on info axis
1888 This is index for Series and columns for DataFrame.
1890 Returns
1891 -------
1892 Generator
1893 """
1894 for h in self._info_axis:
1895 yield h, self[h]
1897 def __len__(self) -> int:
1898 """Returns length of info axis"""
1899 return len(self._info_axis)
1901 @final
1902 def __contains__(self, key) -> bool:
1903 """True if the key is in the info axis"""
1904 return key in self._info_axis
1906 @property
1907 def empty(self) -> bool:
1908 """
1909 Indicator whether Series/DataFrame is empty.
1911 True if Series/DataFrame is entirely empty (no items), meaning any of the
1912 axes are of length 0.
1914 Returns
1915 -------
1916 bool
1917 If Series/DataFrame is empty, return True, if not return False.
1919 See Also
1920 --------
1921 Series.dropna : Return series without null values.
1922 DataFrame.dropna : Return DataFrame with labels on given axis omitted
1923 where (all or any) data are missing.
1925 Notes
1926 -----
1927 If Series/DataFrame contains only NaNs, it is still not considered empty. See
1928 the example below.
1930 Examples
1931 --------
1932 An example of an actual empty DataFrame. Notice the index is empty:
1934 >>> df_empty = pd.DataFrame({"A": []})
1935 >>> df_empty
1936 Empty DataFrame
1937 Columns: [A]
1938 Index: []
1939 >>> df_empty.empty
1940 True
1942 If we only have NaNs in our DataFrame, it is not considered empty! We
1943 will need to drop the NaNs to make the DataFrame empty:
1945 >>> df = pd.DataFrame({"A": [np.nan]})
1946 >>> df
1947 A
1948 0 NaN
1949 >>> df.empty
1950 False
1951 >>> df.dropna().empty
1952 True
1954 >>> ser_empty = pd.Series({"A": []})
1955 >>> ser_empty
1956 A []
1957 dtype: object
1958 >>> ser_empty.empty
1959 False
1960 >>> ser_empty = pd.Series()
1961 >>> ser_empty.empty
1962 True
1963 """
1964 return any(len(self._get_axis(a)) == 0 for a in self._AXIS_ORDERS)
1966 # ----------------------------------------------------------------------
1967 # Array Interface
1969 # This is also set in IndexOpsMixin
1970 # GH#23114 Ensure ndarray.__op__(DataFrame) returns NotImplemented
1971 __array_priority__: int = 1000
1973 def __array__(
1974 self, dtype: npt.DTypeLike | None = None, copy: bool | None = None
1975 ) -> np.ndarray:
1976 if copy is False and not self._mgr.is_single_block and not self.empty:
1977 # check this manually, otherwise ._values will already return a copy
1978 # and np.array(values, copy=False) will not raise an error
1979 raise ValueError(
1980 "Unable to avoid copy while creating an array as requested."
1981 )
1982 values = self._values
1983 if copy is None:
1984 # Note: branch avoids `copy=None` for NumPy 1.x support
1985 arr = np.asarray(values, dtype=dtype)
1986 else:
1987 arr = np.array(values, dtype=dtype, copy=copy)
1989 if (
1990 copy is not True
1991 and astype_is_view(values.dtype, arr.dtype)
1992 and self._mgr.is_single_block
1993 ):
1994 # Check if both conversions can be done without a copy
1995 if astype_is_view(self.dtypes.iloc[0], values.dtype) and astype_is_view(
1996 values.dtype, arr.dtype
1997 ):
1998 arr = arr.view()
1999 arr.flags.writeable = False
2000 return arr
2002 @final
2003 def __array_ufunc__(
2004 self, ufunc: np.ufunc, method: str, *inputs: Any, **kwargs: Any
2005 ):
2006 return arraylike.array_ufunc(self, ufunc, method, *inputs, **kwargs)
2008 # ----------------------------------------------------------------------
2009 # Picklability
2011 @final
2012 def __getstate__(self) -> dict[str, Any]:
2013 meta = {k: getattr(self, k, None) for k in self._metadata}
2014 return {
2015 "_mgr": self._mgr,
2016 "_typ": self._typ,
2017 "_metadata": self._metadata,
2018 "attrs": self.attrs,
2019 "_flags": {k: self.flags[k] for k in self.flags._keys},
2020 **meta,
2021 }
2023 @final
2024 def __setstate__(self, state) -> None:
2025 if isinstance(state, BlockManager):
2026 self._mgr = state
2027 elif isinstance(state, dict):
2028 if "_data" in state and "_mgr" not in state:
2029 # compat for older pickles
2030 state["_mgr"] = state.pop("_data")
2031 typ = state.get("_typ")
2032 if typ is not None:
2033 attrs = state.get("_attrs", {})
2034 if attrs is None: # should not happen, but better be on the safe side
2035 attrs = {}
2036 object.__setattr__(self, "_attrs", attrs)
2037 flags = state.get("_flags", {"allows_duplicate_labels": True})
2038 object.__setattr__(self, "_flags", Flags(self, **flags))
2040 # set in the order of internal names
2041 # to avoid definitional recursion
2042 # e.g. say fill_value needing _mgr to be
2043 # defined
2044 meta = set(self._internal_names + self._metadata)
2045 for k in meta:
2046 # _metadata is handled below: assigning a pre-2.1 pickle's
2047 # ["name"] here would mask the class's ["_name"], see GH#61819
2048 if k in state and k not in ("_flags", "_metadata"):
2049 v = state[k]
2050 object.__setattr__(self, k, v)
2052 if "_metadata" in state:
2053 # merge rather than replace, so a subclass that extends
2054 # _metadata per instance keeps its entries
2055 cls_meta = list(self._metadata)
2056 merged = list(dict.fromkeys(cls_meta + list(state["_metadata"])))
2057 if merged != cls_meta:
2058 object.__setattr__(self, "_metadata", merged)
2060 for k, v in state.items():
2061 if k not in meta:
2062 object.__setattr__(self, k, v)
2064 else:
2065 raise NotImplementedError("Pre-0.12 pickles are no longer supported")
2066 elif len(state) == 2:
2067 raise NotImplementedError("Pre-0.12 pickles are no longer supported")
2069 # ----------------------------------------------------------------------
2070 # Rendering Methods
2072 def __repr__(self) -> str:
2073 # string representation based upon iterating over self
2074 # (since, by definition, `PandasContainers` are iterable)
2075 prepr = f"[{','.join(map(pprint_thing, self))}]"
2076 return f"{type(self).__name__}({prepr})"
2078 @final
2079 def _repr_latex_(self):
2080 """
2081 Returns a LaTeX representation for a particular object.
2082 Mainly for use with nbconvert (jupyter notebook conversion to pdf).
2083 """
2084 if config["styler"]["render"]["repr"] == "latex":
2085 return self.to_latex()
2086 else:
2087 return None
2089 @final
2090 def _repr_data_resource_(self):
2091 """
2092 Not a real Jupyter special repr method, but we use the same
2093 naming convention.
2094 """
2095 if config["display"]["html"]["table_schema"]:
2096 data = self.head(config["display"]["max_rows"])
2098 as_json = data.to_json(orient="table")
2099 as_json = cast("str", as_json)
2100 return loads(as_json, object_pairs_hook=collections.OrderedDict)
2102 # ----------------------------------------------------------------------
2103 # I/O Methods
2105 @final
2106 def to_excel(
2107 self,
2108 excel_writer: FilePath | WriteExcelBuffer | ExcelWriter,
2109 *,
2110 sheet_name: str = "Sheet1",
2111 na_rep: str = "",
2112 float_format: str | None = None,
2113 columns: Sequence[Hashable] | None = None,
2114 header: Sequence[Hashable] | bool = True,
2115 index: bool = True,
2116 index_label: IndexLabel | None = None,
2117 startrow: int = 0,
2118 startcol: int = 0,
2119 engine: Literal["openpyxl", "xlsxwriter"] | None = None,
2120 merge_cells: bool = True,
2121 inf_rep: str = "inf",
2122 freeze_panes: tuple[int, int] | None = None,
2123 storage_options: StorageOptions | None = None,
2124 engine_kwargs: dict[str, Any] | None = None,
2125 autofilter: bool = False,
2126 ) -> None:
2127 """
2128 Write object to an Excel sheet.
2130 To write a single object to an Excel .xlsx file it is only necessary to
2131 specify a target file name. To write to multiple sheets it is necessary to
2132 create an `ExcelWriter` object with a target file name, and specify a sheet
2133 in the file to write to.
2135 Multiple sheets may be written to by specifying unique `sheet_name`.
2136 With all data written to the file it is necessary to save the changes.
2137 Note that creating an `ExcelWriter` object with a file name that already exists
2138 will overwrite the existing file because the default mode is write.
2140 Parameters
2141 ----------
2142 excel_writer : path-like, file-like, or ExcelWriter object
2143 File path or existing ExcelWriter.
2144 sheet_name : str, default 'Sheet1'
2145 Name of sheet which will contain DataFrame.
2146 na_rep : str, default ''
2147 Missing data representation.
2148 float_format : str, optional
2149 Format string for floating point numbers. For example
2150 ``float_format="%.2f"`` will format 0.1234 to 0.12.
2151 columns : sequence or list of str, optional
2152 Columns to write.
2153 header : bool or list of str, default True
2154 Write out the column names. If a list of string is given it is
2155 assumed to be aliases for the column names.
2156 index : bool, default True
2157 Write row names (index).
2158 index_label : str or sequence, optional
2159 Column label for index column(s) if desired. If not specified, and
2160 `header` and `index` are True, then the index names are used. A
2161 sequence should be given if the DataFrame uses MultiIndex.
2162 startrow : int, default 0
2163 Upper left cell row to dump data frame.
2164 startcol : int, default 0
2165 Upper left cell column to dump data frame.
2166 engine : str, optional
2167 Write engine to use, 'openpyxl' or 'xlsxwriter'. You can also set this
2168 via the options ``io.excel.xlsx.writer`` or
2169 ``io.excel.xlsm.writer``.
2170 merge_cells : bool or 'columns', default True
2171 If True, write MultiIndex index and columns as merged cells.
2172 If 'columns', merge MultiIndex column cells only.
2173 inf_rep : str, default 'inf'
2174 Representation for infinity (there is no native representation for
2175 infinity in Excel).
2176 freeze_panes : tuple of int (length 2), optional
2177 Specifies the one-based bottommost row and rightmost column that
2178 is to be frozen.
2179 storage_options : dict, optional
2180 Extra options that make sense for a particular storage connection, e.g.
2181 host, port, username, password, etc. For HTTP(S) URLs the key-value pairs
2182 are forwarded to ``urllib.request.Request`` as header options. For other
2183 URLs (e.g. starting with "s3://", and "gcs://") the key-value pairs are
2184 forwarded to ``fsspec.open``. Please see ``fsspec`` and ``urllib`` for more
2185 details, and for more examples on storage options refer `here
2186 <https://pandas.pydata.org/docs/user_guide/io.html?
2187 highlight=storage_options#reading-writing-remote-files>`_.
2189 engine_kwargs : dict, optional
2190 Arbitrary keyword arguments passed to excel engine.
2191 autofilter : bool, default False
2192 If True, add automatic filters to all columns.
2194 See Also
2195 --------
2196 to_csv : Write DataFrame to a comma-separated values (csv) file.
2197 ExcelWriter : Class for writing DataFrame objects into excel sheets.
2198 read_excel : Read an Excel file into a pandas DataFrame.
2199 read_csv : Read a comma-separated values (csv) file into DataFrame.
2200 io.formats.style.Styler.to_excel : Add styles to Excel sheet.
2202 Notes
2203 -----
2204 For compatibility with :meth:`~DataFrame.to_csv`,
2205 to_excel serializes lists and dicts to strings before writing.
2207 Once a workbook has been saved it is not possible to write further
2208 data without rewriting the whole workbook.
2210 pandas will check the number of rows, columns,
2211 and cell character count does not exceed Excel's limitations.
2212 All other limitations must be checked by the user.
2214 Examples
2215 --------
2217 Create, write to and save a workbook:
2219 >>> df1 = pd.DataFrame(
2220 ... [["a", "b"], ["c", "d"]],
2221 ... index=["row 1", "row 2"],
2222 ... columns=["col 1", "col 2"],
2223 ... )
2224 >>> df1.to_excel("output.xlsx") # doctest: +SKIP
2226 To specify the sheet name:
2228 >>> df1.to_excel("output.xlsx", sheet_name="Sheet_name_1") # doctest: +SKIP
2230 If you wish to write to more than one sheet in the workbook, it is
2231 necessary to specify an ExcelWriter object:
2233 >>> df2 = df1.copy()
2234 >>> with pd.ExcelWriter("output.xlsx") as writer: # doctest: +SKIP
2235 ... df1.to_excel(writer, sheet_name="Sheet_name_1")
2236 ... df2.to_excel(writer, sheet_name="Sheet_name_2")
2238 ExcelWriter can also be used to append to an existing Excel file:
2240 >>> with pd.ExcelWriter("output.xlsx", mode="a") as writer: # doctest: +SKIP
2241 ... df1.to_excel(writer, sheet_name="Sheet_name_3")
2243 To set the library that is used to write the Excel file,
2244 you can pass the `engine` keyword (the default engine is
2245 automatically chosen depending on the file extension):
2247 >>> df1.to_excel("output1.xlsx", engine="xlsxwriter") # doctest: +SKIP
2248 """
2249 if engine_kwargs is None:
2250 engine_kwargs = {}
2252 df = self if isinstance(self, ABCDataFrame) else self.to_frame()
2254 from pandas.io.formats.excel import ExcelFormatter
2256 formatter = ExcelFormatter(
2257 df,
2258 na_rep=na_rep,
2259 cols=columns,
2260 header=header,
2261 float_format=float_format,
2262 index=index,
2263 index_label=index_label,
2264 merge_cells=merge_cells,
2265 inf_rep=inf_rep,
2266 autofilter=autofilter,
2267 )
2268 formatter.write(
2269 excel_writer,
2270 sheet_name=sheet_name,
2271 startrow=startrow,
2272 startcol=startcol,
2273 freeze_panes=freeze_panes,
2274 engine=engine,
2275 storage_options=storage_options,
2276 engine_kwargs=engine_kwargs,
2277 )
2279 @final
2280 def to_json(
2281 self,
2282 path_or_buf: FilePath | WriteBuffer[bytes] | WriteBuffer[str] | None = None,
2283 *,
2284 orient: (
2285 Literal["split", "records", "index", "table", "columns", "values"] | None
2286 ) = None,
2287 date_format: str | None = None,
2288 double_precision: int = 10,
2289 force_ascii: bool = True,
2290 date_unit: TimeUnit = "ms",
2291 default_handler: Callable[[Any], JSONSerializable] | None = None,
2292 lines: bool = False,
2293 compression: CompressionOptions = "infer",
2294 index: bool | None = None,
2295 indent: int | None = None,
2296 storage_options: StorageOptions | None = None,
2297 mode: Literal["a", "w"] = "w",
2298 ) -> str | None:
2299 """
2300 Convert the object to a JSON string.
2302 Note NaN's and None will be converted to null and datetime objects
2303 will be converted to UNIX timestamps.
2305 Parameters
2306 ----------
2307 path_or_buf : str, path object, file-like object, or None, default None
2308 String, path object (implementing os.PathLike[str]), or file-like
2309 object implementing a write() function. If None, the result is
2310 returned as a string.
2311 orient : str
2312 Indication of expected JSON string format.
2314 * Series:
2316 - default is 'index'
2317 - allowed values are: {'split', 'records', 'index', 'table'}.
2318 - the format of the JSON string:
2320 - 'split' : dict like {'name' -> name, 'index' -> [index],
2321 'data' -> [values]}
2322 - 'records' : list like [value, ... , value]; the index
2323 labels and the Series name are not included
2324 - 'index' : dict like {index -> value}
2325 - 'table' : dict like {'schema': {schema}, 'data': {data}}
2327 * DataFrame:
2329 - default is 'columns'
2330 - allowed values are: {'split', 'records', 'index', 'columns',
2331 'values', 'table'}.
2332 - the format of the JSON string:
2334 - 'split' : dict like {'index' -> [index], 'columns' -> [columns],
2335 'data' -> [values]}
2336 - 'records' : list like [{column -> value}, ... , {column -> value}]
2337 - 'index' : dict like {index -> {column -> value}}
2338 - 'columns' : dict like {column -> {index -> value}}
2339 - 'values' : just the values array
2340 - 'table' : dict like {'schema': {schema}, 'data': {data}}
2342 For ``orient='table'``, the data component is like ``orient='records'``.
2344 date_format : {None, 'epoch', 'iso'}
2345 Type of date conversion. 'epoch' = epoch milliseconds,
2346 'iso' = ISO8601. The default depends on the `orient`. For
2347 ``orient='table'``, the default is 'iso'. For all other orients,
2348 the default is 'epoch'.
2350 .. deprecated:: 3.0.0
2351 'epoch' date format is deprecated and will be removed in a future
2352 version, please use 'iso' instead.
2354 double_precision : int, default 10
2355 The number of decimal places to use when encoding
2356 floating point values. The possible maximal value is 15.
2357 Passing double_precision greater than 15 will raise a ValueError.
2358 force_ascii : bool, default True
2359 Force encoded string to be ASCII.
2360 date_unit : str, default 'ms' (milliseconds)
2361 The time unit to encode to, governs timestamp and ISO8601
2362 precision. One of 's', 'ms', 'us', 'ns' for second, millisecond,
2363 microsecond, and nanosecond respectively.
2364 default_handler : callable, default None
2365 Handler to call if object cannot otherwise be converted to a
2366 suitable format for JSON. Should receive a single argument which is
2367 the object to convert and return a serialisable object.
2368 lines : bool, default False
2369 If 'orient' is 'records' write out line-delimited json format. Will
2370 throw ValueError if incorrect 'orient' since others are not
2371 list-like.
2373 compression : str or dict, default 'infer'
2374 For on-the-fly compression of the output data. If 'infer' and
2375 'path_or_buf' is path-like, then detect compression from the following
2376 extensions: '.gz',
2377 '.bz2', '.zip', '.xz', '.zst', '.tar', '.tar.gz', '.tar.xz' or '.tar.bz2'
2378 (otherwise no compression).
2379 Set to ``None`` for no compression.
2380 Can also be a dict with key ``'method'`` set to one of
2381 {``'zip'``, ``'gzip'``, ``'bz2'``, ``'zstd'``, ``'xz'``, ``'tar'``} and
2382 other key-value pairs are forwarded to
2383 ``zipfile.ZipFile``, ``gzip.GzipFile``,
2384 ``bz2.BZ2File``, ``zstandard.ZstdCompressor``, ``lzma.LZMAFile`` or
2385 ``tarfile.TarFile``, respectively.
2386 As an example, the following could be passed for faster compression and
2387 to create a reproducible gzip archive:
2388 ``compression={'method': 'gzip', 'compresslevel': 1, 'mtime': 1}``.
2390 index : bool or None, default None
2391 The index is only used when 'orient' is 'split', 'index', 'column',
2392 or 'table'. Of these, 'index' and 'column' do not support
2393 `index=False`. The string 'index' as a column name with empty :class:`Index`
2394 or if it is 'index' will raise a ``ValueError``.
2396 indent : int, optional
2397 Length of whitespace used to indent each record.
2399 storage_options : dict, optional
2400 Extra options that make sense for a particular storage connection, e.g.
2401 host, port, username, password, etc. For HTTP(S) URLs the key-value pairs
2402 are forwarded to ``urllib.request.Request`` as header options. For other
2403 URLs (e.g. starting with "s3://", and "gcs://") the key-value pairs are
2404 forwarded to ``fsspec.open``. Please see ``fsspec`` and ``urllib`` for more
2405 details, and for more examples on storage options refer `here
2406 <https://pandas.pydata.org/docs/user_guide/io.html?
2407 highlight=storage_options#reading-writing-remote-files>`_.
2409 mode : str, default 'w' (writing)
2410 Specify the IO mode for output when supplying a path_or_buf.
2411 Accepted args are 'w' (writing) and 'a' (append) only.
2412 mode='a' is only supported when lines is True and orient is 'records'.
2414 Returns
2415 -------
2416 None or str
2417 If path_or_buf is None, returns the resulting json format as a
2418 string. Otherwise returns None.
2420 See Also
2421 --------
2422 read_json : Convert a JSON string to pandas object.
2424 Notes
2425 -----
2426 The behavior of ``indent=0`` varies from the stdlib, which does not
2427 indent the output but does insert newlines. Currently, ``indent=0``
2428 and the default ``indent=None`` are equivalent in pandas, though this
2429 may change in a future release.
2431 ``orient='table'`` contains a 'pandas_version' field under 'schema'.
2432 This stores the version of `pandas` used in the latest revision of the
2433 schema.
2435 Examples
2436 --------
2437 >>> from json import loads, dumps
2438 >>> df = pd.DataFrame(
2439 ... [["a", "b"], ["c", "d"]],
2440 ... index=["row 1", "row 2"],
2441 ... columns=["col 1", "col 2"],
2442 ... )
2444 >>> result = df.to_json(orient="split")
2445 >>> parsed = loads(result)
2446 >>> dumps(parsed, indent=4) # doctest: +SKIP
2447 {
2448 "columns": [
2449 "col 1",
2450 "col 2"
2451 ],
2452 "index": [
2453 "row 1",
2454 "row 2"
2455 ],
2456 "data": [
2457 [
2458 "a",
2459 "b"
2460 ],
2461 [
2462 "c",
2463 "d"
2464 ]
2465 ]
2466 }
2468 Encoding/decoding a Dataframe using ``'records'`` formatted JSON.
2469 Note that index labels are not preserved with this encoding.
2471 >>> result = df.to_json(orient="records")
2472 >>> parsed = loads(result)
2473 >>> dumps(parsed, indent=4) # doctest: +SKIP
2474 [
2475 {
2476 "col 1": "a",
2477 "col 2": "b"
2478 },
2479 {
2480 "col 1": "c",
2481 "col 2": "d"
2482 }
2483 ]
2485 A Series with ``orient="records"`` is encoded as a JSON array of its
2486 values only, without the index labels; with ``lines=True``, each
2487 value is written on its own line:
2489 >>> ser = pd.Series([1, 2, 3])
2490 >>> ser.to_json(orient="records")
2491 '[1,2,3]'
2492 >>> ser.to_json(orient="records", lines=True)
2493 '1\\n2\\n3\\n'
2495 For a Series, the default ``orient="index"`` maps index labels to
2496 values, and ``orient="split"`` has a 'name' entry in place of a
2497 DataFrame's 'columns':
2499 >>> ser.to_json()
2500 '{"0":1,"1":2,"2":3}'
2501 >>> ser.to_json(orient="split")
2502 '{"name":null,"index":[0,1,2],"data":[1,2,3]}'
2504 Encoding/decoding a Dataframe using ``'index'`` formatted JSON:
2506 >>> result = df.to_json(orient="index")
2507 >>> parsed = loads(result)
2508 >>> dumps(parsed, indent=4) # doctest: +SKIP
2509 {
2510 "row 1": {
2511 "col 1": "a",
2512 "col 2": "b"
2513 },
2514 "row 2": {
2515 "col 1": "c",
2516 "col 2": "d"
2517 }
2518 }
2520 Encoding/decoding a Dataframe using ``'columns'`` formatted JSON:
2522 >>> result = df.to_json(orient="columns")
2523 >>> parsed = loads(result)
2524 >>> dumps(parsed, indent=4) # doctest: +SKIP
2525 {
2526 "col 1": {
2527 "row 1": "a",
2528 "row 2": "c"
2529 },
2530 "col 2": {
2531 "row 1": "b",
2532 "row 2": "d"
2533 }
2534 }
2536 Encoding/decoding a Dataframe using ``'values'`` formatted JSON:
2538 >>> result = df.to_json(orient="values")
2539 >>> parsed = loads(result)
2540 >>> dumps(parsed, indent=4) # doctest: +SKIP
2541 [
2542 [
2543 "a",
2544 "b"
2545 ],
2546 [
2547 "c",
2548 "d"
2549 ]
2550 ]
2552 Encoding with Table Schema:
2554 >>> result = df.to_json(orient="table")
2555 >>> parsed = loads(result)
2556 >>> dumps(parsed, indent=4) # doctest: +SKIP
2557 {
2558 "schema": {
2559 "fields": [
2560 {
2561 "name": "index",
2562 "type": "string"
2563 },
2564 {
2565 "name": "col 1",
2566 "type": "string"
2567 },
2568 {
2569 "name": "col 2",
2570 "type": "string"
2571 }
2572 ],
2573 "primaryKey": [
2574 "index"
2575 ],
2576 "pandas_version": "1.4.0"
2577 },
2578 "data": [
2579 {
2580 "index": "row 1",
2581 "col 1": "a",
2582 "col 2": "b"
2583 },
2584 {
2585 "index": "row 2",
2586 "col 1": "c",
2587 "col 2": "d"
2588 }
2589 ]
2590 }
2591 """
2592 from pandas.io import json
2594 if date_format is None and orient == "table":
2595 date_format = "iso"
2596 elif date_format is None:
2597 date_format = "epoch"
2598 # Datetime-like values are written as epoch integers not only from the
2599 # column values but also from the index and (for a DataFrame) the
2600 # columns, so check all of those axes for the deprecation warning
2601 # (GH#65868).
2602 if self.ndim == 2:
2603 dtypes = [*self.dtypes, self.index.dtype, self.columns.dtype]
2604 else:
2605 dtypes = [self.dtype, self.index.dtype]
2606 if any(dtype.kind in "mM" for dtype in dtypes):
2607 warnings.warn(
2608 "The default formatting of datetime/timedelta values will change "
2609 'from numbers ("epoch") to strings ("iso") in a future version. '
2610 'Specify `date_format="iso"` explicitly in the `to_json()` call '
2611 "to opt-in to the future behaviour and silence this warning.",
2612 Pandas4Warning,
2613 stacklevel=find_stack_level(),
2614 )
2615 elif date_format == "epoch":
2616 # GH#57063
2617 warnings.warn(
2618 "'epoch' date format is deprecated and will be removed in a future "
2619 "version, please use 'iso' date format instead.",
2620 Pandas4Warning,
2621 stacklevel=find_stack_level(),
2622 )
2624 cf.is_nonnegative_int(indent)
2625 indent = indent or 0
2627 return json.to_json(
2628 path_or_buf=path_or_buf,
2629 obj=self,
2630 orient=orient,
2631 date_format=date_format,
2632 double_precision=double_precision,
2633 force_ascii=force_ascii,
2634 date_unit=date_unit,
2635 default_handler=default_handler,
2636 lines=lines,
2637 compression=compression,
2638 index=index,
2639 indent=indent,
2640 storage_options=storage_options,
2641 mode=mode,
2642 )
2644 @final
2645 def to_hdf(
2646 self,
2647 path_or_buf: FilePath | HDFStore,
2648 *,
2649 key: str,
2650 mode: Literal["a", "w", "r+"] = "a",
2651 complevel: int | None = None,
2652 complib: Literal["zlib", "lzo", "bzip2", "blosc"] | None = None,
2653 append: bool = False,
2654 format: Literal["fixed", "table"] | None = None,
2655 index: bool = True,
2656 min_itemsize: int | dict[str, int] | None = None,
2657 nan_rep=None,
2658 dropna: bool | lib.NoDefault | None = lib.no_default,
2659 data_columns: Literal[True] | list[str] | None = None,
2660 errors: OpenFileErrors = "strict",
2661 encoding: str = "UTF-8",
2662 ) -> None:
2663 """
2664 Write the contained data to an HDF5 file using HDFStore.
2666 Hierarchical Data Format (HDF) is self-describing, allowing an
2667 application to interpret the structure and contents of a file with
2668 no outside information. One HDF file can hold a mix of related objects
2669 which can be accessed as a group or as individual objects.
2671 In order to add another DataFrame or Series to an existing HDF file
2672 please use append mode and a different a key.
2674 .. note::
2676 Files produced by this method use a pandas-specific layout on top
2677 of PyTables and are intended to be read back with :func:`read_hdf`
2678 or :class:`HDFStore`. They are valid HDF5 files but are not a
2679 general-purpose interchange format for arbitrary HDF5 consumers.
2681 .. warning::
2683 One can store a subclass of ``DataFrame`` or ``Series`` to HDF5,
2684 but the type of the subclass is lost upon storing.
2686 For more information see the :ref:`user guide <io.hdf5>`.
2688 Parameters
2689 ----------
2690 path_or_buf : str or pandas.HDFStore
2691 File path or HDFStore object.
2692 key : str
2693 Identifier for the group in the store.
2694 mode : {'a', 'w', 'r+'}, default 'a'
2695 Mode to open file:
2697 - 'w': write, a new file is created (an existing file with
2698 the same name would be deleted).
2699 - 'a': append, an existing file is opened for reading and
2700 writing, and if the file does not exist it is created.
2701 - 'r+': similar to 'a', but the file must already exist.
2702 complevel : {0-9}, default None
2703 Specifies a compression level for data.
2704 A value of 0 or None disables compression.
2705 complib : {'zlib', 'lzo', 'bzip2', 'blosc'}, default 'zlib'
2706 Specifies the compression library to be used. This has no effect
2707 unless ``complevel`` is set to a value greater than 0; passing
2708 ``complib`` alone emits a ``UserWarning`` and writes the data
2709 uncompressed.
2710 These additional compressors for Blosc are supported
2711 (default if no compressor specified: 'blosc:blosclz'):
2712 {'blosc:blosclz', 'blosc:lz4', 'blosc:lz4hc', 'blosc:snappy',
2713 'blosc:zlib', 'blosc:zstd'}.
2714 Specifying a compression library which is not available issues
2715 a ValueError.
2716 append : bool, default False
2717 For Table formats, append the input data to the existing table.
2718 The object stored at ``key`` (if any) must already be in
2719 ``'table'`` format; appending to a ``'fixed'`` object raises
2720 ``ValueError``. When creating a new key with ``append=True``,
2721 ``format`` defaults to ``'table'``. Each append must use exactly
2722 the same columns, in the same order, as the existing table.
2723 format : {'fixed', 'table', None}, default 'fixed'
2724 Possible values:
2726 - 'fixed': Fixed format. Fast writing/reading. Not-appendable,
2727 nor searchable.
2728 - 'table': Table format. Write as a PyTables Table structure
2729 which may perform worse but allow more flexible operations
2730 like searching / selecting subsets of the data.
2731 - If None, pd.get_option('io.hdf.default_format') is checked,
2732 followed by fallback to "fixed".
2733 index : bool, default True
2734 Write DataFrame index as a column.
2735 min_itemsize : dict or int, optional
2736 Map column names to minimum string sizes for columns.
2737 nan_rep : str, optional
2738 String used on disk to represent missing values in string columns
2739 (``format="table"`` only).
2740 By default a sentinel that collides with no value in the column is
2741 used, so a literal ``"nan"`` round-trips unchanged; when this is
2742 passed, a value equal to it is read back as a missing value.
2743 Only used when the table is created; ignored on later appends,
2744 which reuse whatever the table already stores.
2745 dropna : bool, default False, optional
2746 Remove missing values.
2748 .. deprecated:: 3.1.0
2749 The ``dropna`` keyword is deprecated and will be removed in a
2750 future version. Use :meth:`DataFrame.dropna` before writing
2751 instead.
2752 data_columns : list of columns or True, optional
2753 List of columns to create as indexed data columns for on-disk
2754 queries, or True to use all columns. By default only the axes
2755 of the object are indexed. See
2756 :ref:`Query via data columns<io.hdf5-query-data-columns>`. for
2757 more information.
2758 Applicable only to format='table'.
2759 errors : str, default 'strict'
2760 Specifies how encoding and decoding errors are to be handled.
2761 See the errors argument for :func:`open` for a full list
2762 of options.
2763 encoding : str, default "UTF-8"
2764 Set character encoding.
2766 See Also
2767 --------
2768 read_hdf : Read from HDF file.
2769 DataFrame.to_orc : Write a DataFrame to the binary orc format.
2770 DataFrame.to_parquet : Write a DataFrame to the binary parquet format.
2771 DataFrame.to_sql : Write to a SQL table.
2772 DataFrame.to_feather : Write out feather-format for DataFrames.
2773 DataFrame.to_csv : Write out to a csv file.
2775 Examples
2776 --------
2777 >>> df = pd.DataFrame(
2778 ... {"A": [1, 2, 3], "B": [4, 5, 6]}, index=["a", "b", "c"]
2779 ... ) # doctest: +SKIP
2780 >>> df.to_hdf("data.h5", key="df", mode="w") # doctest: +SKIP
2782 We can add another object to the same file:
2784 >>> s = pd.Series([1, 2, 3, 4]) # doctest: +SKIP
2785 >>> s.to_hdf("data.h5", key="s") # doctest: +SKIP
2787 Reading from HDF file:
2789 >>> pd.read_hdf("data.h5", "df") # doctest: +SKIP
2790 A B
2791 a 1 4
2792 b 2 5
2793 c 3 6
2794 >>> pd.read_hdf("data.h5", "s") # doctest: +SKIP
2795 0 1
2796 1 2
2797 2 3
2798 3 4
2799 dtype: int64
2800 """
2801 from pandas.io import pytables
2803 # Argument 3 to "to_hdf" has incompatible type "NDFrame"; expected
2804 # "Union[DataFrame, Series]" [arg-type]
2805 pytables.to_hdf(
2806 path_or_buf,
2807 key,
2808 self, # type: ignore[arg-type]
2809 mode=mode,
2810 complevel=complevel,
2811 complib=complib,
2812 append=append,
2813 format=format,
2814 index=index,
2815 min_itemsize=min_itemsize,
2816 nan_rep=nan_rep,
2817 dropna=dropna,
2818 data_columns=data_columns,
2819 errors=errors,
2820 encoding=encoding,
2821 )
2823 @final
2824 def to_sql(
2825 self,
2826 name: str,
2827 con,
2828 *,
2829 schema: str | None = None,
2830 if_exists: Literal["fail", "replace", "append", "delete_rows"] = "fail",
2831 index: bool = True,
2832 index_label: IndexLabel | None = None,
2833 chunksize: int | None = None,
2834 dtype: DtypeArg | None = None,
2835 method: Literal["multi"] | Callable | None = None,
2836 ) -> int | None:
2837 """
2838 Write records stored in a DataFrame to a SQL database.
2840 Databases supported by SQLAlchemy [1]_ are supported. Tables can be
2841 newly created, appended to, or overwritten.
2843 .. warning::
2844 The pandas library does not attempt to sanitize inputs provided via a to_sql call.
2845 Please refer to the documentation for the underlying database driver to see if it
2846 will properly prevent injection, or alternatively be advised of a security risk when
2847 executing arbitrary commands in a to_sql call.
2849 Parameters
2850 ----------
2851 name : str
2852 Name of SQL table.
2853 con : ADBC connection, sqlalchemy.engine.(Engine or Connection) or sqlite3.Connection
2854 ADBC provides high performance I/O with native type support, where available.
2855 Using SQLAlchemy makes it possible to use any DB supported by that
2856 library. Legacy support is provided for sqlite3.Connection objects. The user
2857 is responsible for engine disposal and connection closure for the SQLAlchemy
2858 connectable. See `here \
2859 <https://docs.sqlalchemy.org/en/20/core/connections.html>`_.
2860 If passing a sqlalchemy.engine.Connection which is already in a transaction,
2861 the transaction will not be committed. If passing a sqlite3.Connection,
2862 it will not be possible to roll back the record insertion.
2864 schema : str, optional
2865 Specify the schema (if database flavor supports this). If None, use
2866 default schema.
2867 if_exists : {'fail', 'replace', 'append', 'delete_rows'}, default 'fail'
2868 How to behave if the table already exists.
2870 * fail: Raise a ValueError.
2871 * replace: Drop the table before inserting new values.
2872 * append: Insert new values to the existing table.
2873 * delete_rows: If a table exists, delete all records and insert data.
2875 index : bool, default True
2876 Write DataFrame index as a column. Uses `index_label` as the column
2877 name in the table. Creates a table index for this column.
2878 index_label : str or sequence, default None
2879 Column label for index column(s). If None is given (default) and
2880 `index` is True, then the index names are used.
2881 A sequence should be given if the DataFrame uses MultiIndex.
2882 chunksize : int, optional
2883 Specify the number of rows in each batch to be written to the database connection at a time.
2884 By default, all rows will be written at once. Also see the method keyword.
2885 dtype : dict or scalar, optional
2886 Specifying the datatype for columns. If a dictionary is used, the
2887 keys should be the column names and the values should be the
2888 SQLAlchemy types or strings for the sqlite3 legacy mode. If a
2889 scalar is provided, it will be applied to all columns.
2890 method : {None, 'multi', callable}, optional
2891 Controls the SQL insertion clause used:
2893 * None : Uses standard SQL ``INSERT`` clause (one per row).
2894 * 'multi': Pass multiple values in a single ``INSERT`` clause.
2895 * callable with signature ``(pd_table, conn, keys, data_iter)``.
2897 Details and a sample callable implementation can be found in the
2898 section :ref:`insert method <io.sql.method>`.
2900 Returns
2901 -------
2902 None or int
2903 Number of rows affected by to_sql. None is returned if the callable
2904 passed into ``method`` does not return an integer number of rows.
2906 The number of returned rows affected is the sum of the ``rowcount``
2907 attribute of ``sqlite3.Cursor`` or SQLAlchemy connectable which may not
2908 reflect the exact number of written rows as stipulated in the
2909 `sqlite3 <https://docs.python.org/3/library/sqlite3.html#sqlite3.Cursor.rowcount>`__ or
2910 `SQLAlchemy <https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.CursorResult.rowcount>`__.
2912 Raises
2913 ------
2914 ValueError
2915 When the table already exists and `if_exists` is 'fail' (the
2916 default).
2918 See Also
2919 --------
2920 read_sql : Read a DataFrame from a table.
2922 Notes
2923 -----
2924 Timezone aware datetime columns will be written as
2925 ``Timestamp with timezone`` type with SQLAlchemy if supported by the
2926 database. Otherwise, the datetimes will be stored as timezone unaware
2927 timestamps local to the original timezone.
2929 Not all datastores support ``method="multi"``. Oracle, for example,
2930 does not support multi-value insert.
2932 When using SQL Server with pyodbc and ``fast_executemany=True``, datetime
2933 precision may be lost when writing to local temporary tables (names starting
2934 with ``#``). To avoid this, add ``UseFMTONLY=Yes`` to the connection string.
2935 See :ref:`io.sql_datetime_data` for details.
2937 References
2938 ----------
2939 .. [1] https://docs.sqlalchemy.org
2940 .. [2] https://www.python.org/dev/peps/pep-0249/
2942 Examples
2943 --------
2944 Create an in-memory SQLite database.
2946 >>> from sqlalchemy import create_engine
2947 >>> engine = create_engine('sqlite://', echo=False)
2949 Create a table from scratch with 3 rows.
2951 >>> df = pd.DataFrame({'name' : ['User 1', 'User 2', 'User 3']})
2952 >>> df
2953 name
2954 0 User 1
2955 1 User 2
2956 2 User 3
2958 >>> df.to_sql(name='users', con=engine)
2959 3
2960 >>> from sqlalchemy import text
2961 >>> with engine.connect() as conn:
2962 ... conn.execute(text("SELECT * FROM users")).fetchall()
2963 [(0, 'User 1'), (1, 'User 2'), (2, 'User 3')]
2965 An `sqlalchemy.engine.Connection` can also be passed to `con`:
2967 >>> with engine.begin() as connection:
2968 ... df1 = pd.DataFrame({'name' : ['User 4', 'User 5']})
2969 ... df1.to_sql(name='users', con=connection, if_exists='append')
2970 2
2972 This is allowed to support operations that require that the same
2973 DBAPI connection is used for the entire operation.
2975 >>> df2 = pd.DataFrame({'name' : ['User 6', 'User 7']})
2976 >>> df2.to_sql(name='users', con=engine, if_exists='append')
2977 2
2978 >>> with engine.connect() as conn:
2979 ... conn.execute(text("SELECT * FROM users")).fetchall()
2980 [(0, 'User 1'), (1, 'User 2'), (2, 'User 3'),
2981 (0, 'User 4'), (1, 'User 5'), (0, 'User 6'),
2982 (1, 'User 7')]
2984 Overwrite the table with just ``df2``.
2986 >>> df2.to_sql(name='users', con=engine, if_exists='replace',
2987 ... index_label='id')
2988 2
2989 >>> with engine.connect() as conn:
2990 ... conn.execute(text("SELECT * FROM users")).fetchall()
2991 [(0, 'User 6'), (1, 'User 7')]
2993 Delete all rows before inserting new records with ``df3``
2995 >>> df3 = pd.DataFrame({"name": ['User 8', 'User 9']})
2996 >>> df3.to_sql(name='users', con=engine, if_exists='delete_rows',
2997 ... index_label='id')
2998 2
2999 >>> with engine.connect() as conn:
3000 ... conn.execute(text("SELECT * FROM users")).fetchall()
3001 [(0, 'User 8'), (1, 'User 9')]
3003 Use ``method`` to define a callable insertion method to do nothing
3004 if there's a primary key conflict on a table in a PostgreSQL database.
3006 >>> from sqlalchemy.dialects.postgresql import insert
3007 >>> def insert_on_conflict_nothing(table, conn, keys, data_iter):
3008 ... # "a" is the primary key in "conflict_table"
3009 ... data = [dict(zip(keys, row)) for row in data_iter]
3010 ... stmt = insert(table.table).values(data).on_conflict_do_nothing(index_elements=["a"])
3011 ... result = conn.execute(stmt)
3012 ... return result.rowcount
3013 >>> df_conflict.to_sql(name="conflict_table", con=conn, if_exists="append", # noqa: F821
3014 ... method=insert_on_conflict_nothing) # doctest: +SKIP
3015 0
3017 For MySQL, a callable to update columns ``b`` and ``c`` if there's a conflict
3018 on a primary key.
3020 >>> from sqlalchemy.dialects.mysql import insert # noqa: F811
3021 >>> def insert_on_conflict_update(table, conn, keys, data_iter):
3022 ... # update columns "b" and "c" on primary key conflict
3023 ... data = [dict(zip(keys, row)) for row in data_iter]
3024 ... stmt = (
3025 ... insert(table.table)
3026 ... .values(data)
3027 ... )
3028 ... stmt = stmt.on_duplicate_key_update(b=stmt.inserted.b, c=stmt.inserted.c)
3029 ... result = conn.execute(stmt)
3030 ... return result.rowcount
3031 >>> df_conflict.to_sql(name="conflict_table", con=conn, if_exists="append", # noqa: F821
3032 ... method=insert_on_conflict_update) # doctest: +SKIP
3033 2
3035 Specify the dtype (especially useful for integers with missing values).
3036 Notice that while pandas is forced to store the data as floating point,
3037 the database supports nullable integers. When fetching the data with
3038 Python, we get back integer scalars.
3040 >>> df = pd.DataFrame({"A": [1, None, 2]})
3041 >>> df
3042 A
3043 0 1.0
3044 1 NaN
3045 2 2.0
3047 >>> from sqlalchemy.types import Integer
3048 >>> df.to_sql(name='integers', con=engine, index=False,
3049 ... dtype={"A": Integer()})
3050 3
3052 >>> with engine.connect() as conn:
3053 ... conn.execute(text("SELECT * FROM integers")).fetchall()
3054 [(1,), (None,), (2,)]
3056 .. versionadded:: 2.2.0
3058 pandas now supports writing via ADBC drivers
3060 >>> df = pd.DataFrame({'name' : ['User 10', 'User 11', 'User 12']})
3061 >>> df
3062 name
3063 0 User 10
3064 1 User 11
3065 2 User 12
3067 >>> from adbc_driver_sqlite import dbapi # doctest:+SKIP
3068 >>> with dbapi.connect("sqlite://") as conn: # doctest:+SKIP
3069 ... df.to_sql(name="users", con=conn)
3070 3
3071 """ # noqa: E501
3072 from pandas.io import sql
3074 return sql.to_sql(
3075 self,
3076 name,
3077 con,
3078 schema=schema,
3079 if_exists=if_exists,
3080 index=index,
3081 index_label=index_label,
3082 chunksize=chunksize,
3083 dtype=dtype,
3084 method=method,
3085 )
3087 @final
3088 def to_pickle(
3089 self,
3090 path: FilePath | WriteBuffer[bytes],
3091 *,
3092 compression: CompressionOptions = "infer",
3093 protocol: int = pickle.HIGHEST_PROTOCOL,
3094 storage_options: StorageOptions | None = None,
3095 ) -> None:
3096 """
3097 Pickle (serialize) object to file.
3099 Uses Python's ``pickle`` module to serialize the object and write
3100 it to the specified file path. The resulting file can be loaded
3101 back using :func:`pandas.read_pickle`.
3103 Parameters
3104 ----------
3105 path : str, path object, or file-like object
3106 String, path object (implementing ``os.PathLike[str]``), or file-like
3107 object implementing a binary ``write()`` function. File path where
3108 the pickled object will be stored.
3110 compression : str or dict, default 'infer'
3111 For on-the-fly compression of the output data. If 'infer' and
3112 'path_or_buf' is path-like, then detect compression from the following
3113 extensions: '.gz',
3114 '.bz2', '.zip', '.xz', '.zst', '.tar', '.tar.gz', '.tar.xz' or '.tar.bz2'
3115 (otherwise no compression).
3116 Set to ``None`` for no compression.
3117 Can also be a dict with key ``'method'`` set to one of
3118 {``'zip'``, ``'gzip'``, ``'bz2'``, ``'zstd'``, ``'xz'``, ``'tar'``} and
3119 other key-value pairs are forwarded to
3120 ``zipfile.ZipFile``, ``gzip.GzipFile``,
3121 ``bz2.BZ2File``, ``zstandard.ZstdCompressor``, ``lzma.LZMAFile`` or
3122 ``tarfile.TarFile``, respectively.
3123 As an example, the following could be passed for faster compression and
3124 to create a reproducible gzip archive:
3125 ``compression={'method': 'gzip', 'compresslevel': 1, 'mtime': 1}``.
3127 protocol : int
3128 Int which indicates which protocol should be used by the pickler,
3129 default HIGHEST_PROTOCOL (see [1]_ paragraph 12.1.2). The possible
3130 values are 0, 1, 2, 3, 4, 5. A negative value for the protocol
3131 parameter is equivalent to setting its value to HIGHEST_PROTOCOL.
3133 .. [1] https://docs.python.org/3/library/pickle.html.
3135 storage_options : dict, optional
3136 Extra options that make sense for a particular storage connection, e.g.
3137 host, port, username, password, etc. For HTTP(S) URLs the key-value pairs
3138 are forwarded to ``urllib.request.Request`` as header options. For other
3139 URLs (e.g. starting with "s3://", and "gcs://") the key-value pairs are
3140 forwarded to ``fsspec.open``. Please see ``fsspec`` and ``urllib`` for more
3141 details, and for more examples on storage options refer `here
3142 <https://pandas.pydata.org/docs/user_guide/io.html?
3143 highlight=storage_options#reading-writing-remote-files>`_.
3145 See Also
3146 --------
3147 read_pickle : Load pickled pandas object (or any object) from file.
3148 DataFrame.to_hdf : Write DataFrame to an HDF5 file.
3149 DataFrame.to_sql : Write DataFrame to a SQL database.
3150 DataFrame.to_parquet : Write a DataFrame to the binary parquet format.
3152 Examples
3153 --------
3154 >>> original_df = pd.DataFrame(
3155 ... {"foo": range(5), "bar": range(5, 10)}
3156 ... ) # doctest: +SKIP
3157 >>> original_df # doctest: +SKIP
3158 foo bar
3159 0 0 5
3160 1 1 6
3161 2 2 7
3162 3 3 8
3163 4 4 9
3164 >>> original_df.to_pickle("./dummy.pkl") # doctest: +SKIP
3166 >>> unpickled_df = pd.read_pickle("./dummy.pkl") # doctest: +SKIP
3167 >>> unpickled_df # doctest: +SKIP
3168 foo bar
3169 0 0 5
3170 1 1 6
3171 2 2 7
3172 3 3 8
3173 4 4 9
3174 """
3175 from pandas.io.pickle import to_pickle
3177 to_pickle(
3178 self,
3179 path,
3180 compression=compression,
3181 protocol=protocol,
3182 storage_options=storage_options,
3183 )
3185 @final
3186 def to_clipboard(
3187 self, *, excel: bool = True, sep: str | None = None, **kwargs
3188 ) -> None:
3189 r"""
3190 Copy object to the system clipboard.
3192 Write a text representation of object to the system clipboard.
3193 This can be pasted into Excel, for example.
3195 Parameters
3196 ----------
3197 excel : bool, default True
3198 Produce output in a csv format for easy pasting into excel.
3200 - True, use the provided separator for csv pasting.
3201 - False, write a string representation of the object to the clipboard.
3203 sep : str, default ``'\t'``
3204 Field delimiter.
3205 **kwargs
3206 These parameters will be passed to DataFrame.to_csv. If csv output
3207 is not produced (``excel=False`` or an invalid ``sep``), they are
3208 passed to DataFrame.to_string instead, or ignored for a Series.
3210 See Also
3211 --------
3212 DataFrame.to_csv : Write a DataFrame to a comma-separated values
3213 (csv) file.
3214 read_clipboard : Read text from clipboard and pass to read_csv.
3216 Notes
3217 -----
3218 Requirements for your platform.
3220 - Linux : `xclip`, or `xsel` (with `PyQt4` modules)
3221 - Windows : none
3222 - macOS : none
3224 This method uses the processes developed for the package `pyperclip`. A
3225 solution to render any output string format is given in the examples.
3227 Examples
3228 --------
3229 Copy the contents of a DataFrame to the clipboard.
3231 >>> df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=["A", "B", "C"])
3233 >>> df.to_clipboard(sep=",") # doctest: +SKIP
3234 ... # Wrote the following to the system clipboard:
3235 ... # ,A,B,C
3236 ... # 0,1,2,3
3237 ... # 1,4,5,6
3239 We can omit the index by passing the keyword `index` and setting
3240 it to false.
3242 >>> df.to_clipboard(sep=",", index=False) # doctest: +SKIP
3243 ... # Wrote the following to the system clipboard:
3244 ... # A,B,C
3245 ... # 1,2,3
3246 ... # 4,5,6
3248 Using the original `pyperclip` package for any string output format.
3250 .. code-block:: python
3252 import pyperclip
3254 html = df.style.to_html()
3255 pyperclip.copy(html)
3256 """
3257 from pandas.io import clipboards
3259 clipboards.to_clipboard(self, excel=excel, sep=sep, **kwargs)
3261 @final
3262 def to_xarray(self):
3263 """
3264 Return an xarray object from the pandas object.
3266 This method converts a pandas object to an xarray object, which is
3267 useful for working with labeled multi-dimensional data.
3269 Returns
3270 -------
3271 xarray.DataArray or xarray.Dataset
3272 Data in the pandas structure converted to Dataset if the object is
3273 a DataFrame, or a DataArray if the object is a Series.
3275 See Also
3276 --------
3277 DataFrame.to_hdf : Write DataFrame to an HDF5 file.
3278 DataFrame.to_parquet : Write a DataFrame to the binary parquet format.
3280 Notes
3281 -----
3282 See the `xarray docs <https://xarray.pydata.org/en/stable/>`__
3284 Examples
3285 --------
3286 >>> df = pd.DataFrame(
3287 ... [
3288 ... ("falcon", "bird", 389.0, 2),
3289 ... ("parrot", "bird", 24.0, 2),
3290 ... ("lion", "mammal", 80.5, 4),
3291 ... ("monkey", "mammal", np.nan, 4),
3292 ... ],
3293 ... columns=["name", "class", "max_speed", "num_legs"],
3294 ... )
3295 >>> df
3296 name class max_speed num_legs
3297 0 falcon bird 389.0 2
3298 1 parrot bird 24.0 2
3299 2 lion mammal 80.5 4
3300 3 monkey mammal NaN 4
3302 >>> df.to_xarray() # doctest: +SKIP
3303 <xarray.Dataset>
3304 Dimensions: (index: 4)
3305 Coordinates:
3306 * index (index) int64 32B 0 1 2 3
3307 Data variables:
3308 name (index) object 32B 'falcon' 'parrot' 'lion' 'monkey'
3309 class (index) object 32B 'bird' 'bird' 'mammal' 'mammal'
3310 max_speed (index) float64 32B 389.0 24.0 80.5 nan
3311 num_legs (index) int64 32B 2 2 4 4
3313 >>> df["max_speed"].to_xarray() # doctest: +SKIP
3314 <xarray.DataArray 'max_speed' (index: 4)>
3315 array([389. , 24. , 80.5, nan])
3316 Coordinates:
3317 * index (index) int64 0 1 2 3
3319 >>> dates = pd.to_datetime(
3320 ... ["2018-01-01", "2018-01-01", "2018-01-02", "2018-01-02"]
3321 ... )
3322 >>> df_multiindex = pd.DataFrame(
3323 ... {
3324 ... "date": dates,
3325 ... "animal": ["falcon", "parrot", "falcon", "parrot"],
3326 ... "speed": [350, 18, 361, 15],
3327 ... }
3328 ... )
3329 >>> df_multiindex = df_multiindex.set_index(["date", "animal"])
3331 >>> df_multiindex
3332 speed
3333 date animal
3334 2018-01-01 falcon 350
3335 parrot 18
3336 2018-01-02 falcon 361
3337 parrot 15
3339 >>> df_multiindex.to_xarray() # doctest: +SKIP
3340 <xarray.Dataset>
3341 Dimensions: (date: 2, animal: 2)
3342 Coordinates:
3343 * date (date) datetime64[s] 2018-01-01 2018-01-02
3344 * animal (animal) object 'falcon' 'parrot'
3345 Data variables:
3346 speed (date, animal) int64 350 18 361 15
3347 """
3348 xarray = import_optional_dependency("xarray")
3350 if self.ndim == 1:
3351 return xarray.DataArray.from_series(self)
3352 else:
3353 return xarray.Dataset.from_dataframe(self)
3355 @overload
3356 def to_latex(
3357 self,
3358 buf: None = ...,
3359 *,
3360 columns: Sequence[Hashable] | None = ...,
3361 header: bool | SequenceNotStr[str] = ...,
3362 index: bool = ...,
3363 na_rep: str = ...,
3364 formatters: FormattersType | None = ...,
3365 float_format: FloatFormatType | None = ...,
3366 sparsify: bool | None = ...,
3367 index_names: bool = ...,
3368 bold_rows: bool = ...,
3369 column_format: str | None = ...,
3370 longtable: bool | None = ...,
3371 escape: bool | None = ...,
3372 encoding: str | None = ...,
3373 decimal: str = ...,
3374 multicolumn: bool | None = ...,
3375 multicolumn_format: str | None = ...,
3376 multirow: bool | None = ...,
3377 caption: str | tuple[str, str] | None = ...,
3378 label: str | None = ...,
3379 position: str | None = ...,
3380 ) -> str: ...
3382 @overload
3383 def to_latex(
3384 self,
3385 buf: FilePath | WriteBuffer[str],
3386 *,
3387 columns: Sequence[Hashable] | None = ...,
3388 header: bool | SequenceNotStr[str] = ...,
3389 index: bool = ...,
3390 na_rep: str = ...,
3391 formatters: FormattersType | None = ...,
3392 float_format: FloatFormatType | None = ...,
3393 sparsify: bool | None = ...,
3394 index_names: bool = ...,
3395 bold_rows: bool = ...,
3396 column_format: str | None = ...,
3397 longtable: bool | None = ...,
3398 escape: bool | None = ...,
3399 encoding: str | None = ...,
3400 decimal: str = ...,
3401 multicolumn: bool | None = ...,
3402 multicolumn_format: str | None = ...,
3403 multirow: bool | None = ...,
3404 caption: str | tuple[str, str] | None = ...,
3405 label: str | None = ...,
3406 position: str | None = ...,
3407 ) -> None: ...
3409 @final
3410 def to_latex(
3411 self,
3412 buf: FilePath | WriteBuffer[str] | None = None,
3413 *,
3414 columns: Sequence[Hashable] | None = None,
3415 header: bool | SequenceNotStr[str] = True,
3416 index: bool = True,
3417 na_rep: str = "NaN",
3418 formatters: FormattersType | None = None,
3419 float_format: FloatFormatType | None = None,
3420 sparsify: bool | None = None,
3421 index_names: bool = True,
3422 bold_rows: bool = False,
3423 column_format: str | None = None,
3424 longtable: bool | None = None,
3425 escape: bool | None = None,
3426 encoding: str | None = None,
3427 decimal: str = ".",
3428 multicolumn: bool | None = None,
3429 multicolumn_format: str | None = None,
3430 multirow: bool | None = None,
3431 caption: str | tuple[str, str] | None = None,
3432 label: str | None = None,
3433 position: str | None = None,
3434 ) -> str | None:
3435 r"""
3436 Render object to a LaTeX tabular, longtable, or nested table.
3438 Requires ``\usepackage{booktabs}``. The output can be copy/pasted
3439 into a main LaTeX document or read from an external file
3440 with ``\input{table.tex}``.
3442 .. versionchanged:: 2.0.0
3443 Refactored to use the Styler implementation via jinja2 templating.
3445 Parameters
3446 ----------
3447 buf : str, Path or StringIO-like, optional, default None
3448 Buffer to write to. If None, the output is returned as a string.
3449 columns : list of label, optional
3450 The subset of columns to write. Writes all columns by default.
3451 header : bool or list of str, default True
3452 Write out the column names. If a list of strings is given,
3453 it is assumed to be aliases for the column names. Braces must be escaped.
3454 index : bool, default True
3455 Write row names (index).
3456 na_rep : str, default 'NaN'
3457 Missing data representation.
3458 formatters : list of functions or dict of {str: function}, optional
3459 Formatter functions to apply to columns' elements by position or
3460 name. The result of each function must be a unicode string.
3461 List must be of length equal to the number of columns.
3462 float_format : one-parameter function or str, optional, default None
3463 Formatter for floating point numbers. For example
3464 ``float_format="%.2f"`` and ``float_format="{:0.2f}".format`` will
3465 both result in 0.1234 being formatted as 0.12.
3466 sparsify : bool, optional
3467 Set to False for a DataFrame with a hierarchical index to print
3468 every multiindex key at each row. By default, the value will be
3469 read from the config module.
3470 index_names : bool, default True
3471 Prints the names of the indexes.
3472 bold_rows : bool, default False
3473 Make the row labels bold in the output.
3474 column_format : str, optional
3475 The columns format as specified in `LaTeX table format
3476 <https://en.wikibooks.org/wiki/LaTeX/Tables>`__ e.g. 'rcl' for 3
3477 columns. By default, 'l' will be used for all columns except
3478 columns of numbers, which default to 'r'.
3479 longtable : bool, optional
3480 Use a longtable environment instead of tabular. Requires
3481 adding a \usepackage{longtable} to your LaTeX preamble.
3482 By default, the value will be read from the pandas config
3483 module, and set to `True` if the option ``styler.latex.environment`` is
3484 `"longtable"`.
3486 .. versionchanged:: 2.0.0
3487 The pandas option affecting this argument has changed.
3488 escape : bool, optional
3489 By default, the value will be read from the pandas config
3490 module and set to `True` if the option ``styler.format.escape`` is
3491 `"latex"`. When set to False prevents from escaping latex special
3492 characters in column names.
3494 .. versionchanged:: 2.0.0
3495 The pandas option affecting this argument has changed, as has the
3496 default value to `False`.
3497 encoding : str, optional
3498 A string representing the encoding to use in the output file,
3499 defaults to 'utf-8'.
3500 decimal : str, default '.'
3501 Character recognized as decimal separator, e.g. ',' in Europe.
3502 multicolumn : bool, default True
3503 Use \multicolumn to enhance MultiIndex columns.
3504 The default will be read from the config module, and is set
3505 as the option ``styler.sparse.columns``.
3507 .. versionchanged:: 2.0.0
3508 The pandas option affecting this argument has changed.
3509 multicolumn_format : str, default 'r'
3510 The alignment for multicolumns, similar to `column_format`
3511 The default will be read from the config module, and is set as the option
3512 ``styler.latex.multicol_align``.
3514 .. versionchanged:: 2.0.0
3515 The pandas option affecting this argument has changed, as has the
3516 default value to "r".
3517 multirow : bool, default True
3518 Use \multirow to enhance MultiIndex rows. Requires adding a
3519 \usepackage{multirow} to your LaTeX preamble. Will print
3520 centered labels (instead of top-aligned) across the contained
3521 rows, separating groups via clines. The default will be read
3522 from the pandas config module, and is set as the option
3523 ``styler.sparse.index``.
3525 .. versionchanged:: 2.0.0
3526 The pandas option affecting this argument has changed, as has the
3527 default value to `True`.
3528 caption : str or tuple, optional
3529 Tuple (full_caption, short_caption),
3530 which results in ``\caption[short_caption]{full_caption}``;
3531 if a single string is passed, no short caption will be set.
3532 label : str, optional
3533 The LaTeX label to be placed inside ``\label{}`` in the output.
3534 This is used with ``\ref{}`` in the main ``.tex`` file.
3536 position : str, optional
3537 The LaTeX positional argument for tables, to be placed after
3538 ``\begin{}`` in the output.
3540 Returns
3541 -------
3542 str or None
3543 If buf is None, returns the result as a string. Otherwise returns None.
3545 See Also
3546 --------
3547 io.formats.style.Styler.to_latex : Render a DataFrame to LaTeX
3548 with conditional formatting.
3549 DataFrame.to_string : Render a DataFrame to a console-friendly
3550 tabular output.
3551 DataFrame.to_html : Render a DataFrame as an HTML table.
3553 Notes
3554 -----
3555 As of v2.0.0 this method has changed to use the Styler implementation as
3556 part of :meth:`.Styler.to_latex` via ``jinja2`` templating. This means
3557 that ``jinja2`` is a requirement, and needs to be installed, for this method
3558 to function. It is advised that users switch to using Styler, since that
3559 implementation is more frequently updated and contains much more
3560 flexibility with the output.
3562 Examples
3563 --------
3564 Convert a general DataFrame to LaTeX with formatting:
3566 >>> df = pd.DataFrame(dict(name=['Raphael', 'Donatello'],
3567 ... age=[26, 45],
3568 ... height=[181.23, 177.65]))
3569 >>> print(df.to_latex(index=False,
3570 ... formatters={"name": str.upper},
3571 ... float_format="{:.1f}".format,
3572 ... )) # doctest: +SKIP
3573 \begin{tabular}{lrr}
3574 \toprule
3575 name & age & height \\
3576 \midrule
3577 RAPHAEL & 26 & 181.2 \\
3578 DONATELLO & 45 & 177.7 \\
3579 \bottomrule
3580 \end{tabular}
3581 """
3582 # Get defaults from the pandas config
3583 if self.ndim == 1:
3584 self = self.to_frame()
3585 if longtable is None:
3586 longtable = config["styler"]["latex"]["environment"] == "longtable"
3587 if escape is None:
3588 escape = config["styler"]["format"]["escape"] == "latex"
3589 if multicolumn is None:
3590 multicolumn = config["styler"]["sparse"]["columns"]
3591 if multicolumn_format is None:
3592 multicolumn_format = config["styler"]["latex"]["multicol_align"]
3593 if multirow is None:
3594 multirow = config["styler"]["sparse"]["index"]
3596 if column_format is not None and not isinstance(column_format, str):
3597 raise ValueError("`column_format` must be str or unicode")
3598 length = len(self.columns) if columns is None else len(columns)
3599 if isinstance(header, (list, tuple)) and len(header) != length:
3600 raise ValueError(f"Writing {length} cols but got {len(header)} aliases")
3602 # Refactor formatters/float_format/decimal/na_rep/escape to Styler structure
3603 base_format_ = {
3604 "na_rep": na_rep,
3605 "escape": "latex" if escape else None,
3606 "decimal": decimal,
3607 }
3608 index_format_: dict[str, Any] = {"axis": 0, **base_format_}
3609 column_format_: dict[str, Any] = {"axis": 1, **base_format_}
3611 if isinstance(float_format, str):
3612 float_format_: Callable | None = lambda x: float_format % x
3613 else:
3614 float_format_ = float_format
3616 def _wrap(x, alt_format_):
3617 if isinstance(x, (float, complex)) and float_format_ is not None:
3618 return float_format_(x)
3619 else:
3620 return alt_format_(x)
3622 formatters_: list | tuple | dict | Callable | None = None
3623 if isinstance(formatters, list):
3624 formatters_ = {
3625 c: partial(_wrap, alt_format_=formatters[i])
3626 for i, c in enumerate(self.columns)
3627 }
3628 elif isinstance(formatters, dict):
3629 index_formatter = formatters.pop("__index__", None)
3630 column_formatter = formatters.pop("__columns__", None)
3631 if index_formatter is not None:
3632 index_format_.update({"formatter": index_formatter})
3633 if column_formatter is not None:
3634 column_format_.update({"formatter": column_formatter})
3636 formatters_ = formatters
3637 float_columns = self.select_dtypes(include="float").columns
3638 for col in float_columns:
3639 if col not in formatters.keys():
3640 formatters_.update({col: float_format_})
3641 elif formatters is None and float_format is not None:
3642 formatters_ = partial(_wrap, alt_format_=lambda v: v)
3643 format_index_ = [index_format_, column_format_]
3644 format_index_names_ = [index_format_, column_format_]
3646 # Deal with hiding indexes and relabelling column names
3647 hide_: list[dict] = []
3648 relabel_index_: list[dict] = []
3649 if columns:
3650 hide_.append(
3651 {
3652 "subset": [c for c in self.columns if c not in columns],
3653 "axis": "columns",
3654 }
3655 )
3656 if header is False:
3657 hide_.append({"axis": "columns"})
3658 elif isinstance(header, (list, tuple)):
3659 relabel_index_.append({"labels": header, "axis": "columns"})
3660 format_index_ = [index_format_] # column_format is overwritten
3662 if index is False:
3663 hide_.append({"axis": "index"})
3664 if index_names is False:
3665 hide_.append({"names": True, "axis": "index"})
3667 render_kwargs_ = {
3668 "hrules": True,
3669 "sparse_index": sparsify,
3670 "sparse_columns": sparsify,
3671 "environment": "longtable" if longtable else None,
3672 "multicol_align": (
3673 multicolumn_format if multicolumn else f"naive-{multicolumn_format}"
3674 ),
3675 "multirow_align": "t" if multirow else "naive",
3676 "encoding": encoding,
3677 "caption": caption,
3678 "label": label,
3679 "position": position,
3680 "column_format": column_format,
3681 "clines": (
3682 "skip-last;data"
3683 if (multirow and isinstance(self.index, MultiIndex))
3684 else None
3685 ),
3686 "bold_rows": bold_rows,
3687 }
3689 return self._to_latex_via_styler(
3690 buf,
3691 hide=hide_,
3692 relabel_index=relabel_index_,
3693 format={"formatter": formatters_, **base_format_},
3694 format_index=format_index_,
3695 format_index_names=format_index_names_,
3696 render_kwargs=render_kwargs_,
3697 )
3699 @final
3700 def _to_latex_via_styler(
3701 self,
3702 buf=None,
3703 *,
3704 hide: dict | list[dict] | None = None,
3705 relabel_index: dict | list[dict] | None = None,
3706 format: dict | list[dict] | None = None,
3707 format_index: dict | list[dict] | None = None,
3708 format_index_names: dict | list[dict] | None = None,
3709 render_kwargs: dict | None = None,
3710 ):
3711 """
3712 Render object to a LaTeX tabular, longtable, or nested table.
3714 Uses the ``Styler`` implementation with the following, ordered, method chaining:
3716 .. code-block:: python
3717 styler = Styler(DataFrame)
3718 styler.hide(**hide)
3719 styler.relabel_index(**relabel_index)
3720 styler.format(**format)
3721 styler.format_index(**format_index)
3722 styler.to_latex(buf=buf, **render_kwargs)
3724 Parameters
3725 ----------
3726 buf : str, Path or StringIO-like, optional, default None
3727 Buffer to write to. If None, the output is returned as a string.
3728 hide : dict, list of dict
3729 Keyword args to pass to the method call of ``Styler.hide``. If a list will
3730 call the method numerous times.
3731 relabel_index : dict, list of dict
3732 Keyword args to pass to the method of ``Styler.relabel_index``. If a list
3733 will call the method numerous times.
3734 format : dict, list of dict
3735 Keyword args to pass to the method call of ``Styler.format``. If a list will
3736 call the method numerous times.
3737 format_index : dict, list of dict
3738 Keyword args to pass to the method call of ``Styler.format_index``. If a
3739 list will call the method numerous times.
3740 render_kwargs : dict
3741 Keyword args to pass to the method call of ``Styler.to_latex``.
3743 Returns
3744 -------
3745 str or None
3746 If buf is None, returns the result as a string. Otherwise returns None.
3747 """
3748 from pandas.io.formats.style import Styler
3750 self = cast("DataFrame", self)
3751 styler = Styler(self, uuid="")
3753 for kw_name in [
3754 "hide",
3755 "relabel_index",
3756 "format",
3757 "format_index",
3758 "format_index_names",
3759 ]:
3760 kw = vars()[kw_name]
3761 if isinstance(kw, dict):
3762 getattr(styler, kw_name)(**kw)
3763 elif isinstance(kw, list):
3764 for sub_kw in kw:
3765 getattr(styler, kw_name)(**sub_kw)
3767 # bold_rows is not a direct kwarg of Styler.to_latex
3768 render_kwargs = {} if render_kwargs is None else render_kwargs
3769 if render_kwargs.pop("bold_rows"):
3770 styler.map_index(lambda v: "textbf:--rwrap;")
3772 return styler.to_latex(buf=buf, **render_kwargs)
3774 @overload
3775 def to_csv(
3776 self,
3777 path_or_buf: None = ...,
3778 *,
3779 sep: str = ...,
3780 na_rep: str = ...,
3781 float_format: str | Callable | None = ...,
3782 columns: Sequence[Hashable] | None = ...,
3783 header: bool | list[str] = ...,
3784 index: bool = ...,
3785 index_label: IndexLabel | None = ...,
3786 mode: str = ...,
3787 encoding: str | None = ...,
3788 compression: CompressionOptions = ...,
3789 quoting: int | None = ...,
3790 quotechar: str = ...,
3791 lineterminator: str | None = ...,
3792 chunksize: int | None = ...,
3793 date_format: str | None = ...,
3794 doublequote: bool = ...,
3795 escapechar: str | None = ...,
3796 decimal: str = ...,
3797 errors: OpenFileErrors = ...,
3798 storage_options: StorageOptions = ...,
3799 ) -> str: ...
3801 @overload
3802 def to_csv(
3803 self,
3804 path_or_buf: FilePath | WriteBuffer[bytes] | WriteBuffer[str],
3805 *,
3806 sep: str = ...,
3807 na_rep: str = ...,
3808 float_format: str | Callable | None = ...,
3809 columns: Sequence[Hashable] | None = ...,
3810 header: bool | list[str] = ...,
3811 index: bool = ...,
3812 index_label: IndexLabel | None = ...,
3813 mode: str = ...,
3814 encoding: str | None = ...,
3815 compression: CompressionOptions = ...,
3816 quoting: int | None = ...,
3817 quotechar: str = ...,
3818 lineterminator: str | None = ...,
3819 chunksize: int | None = ...,
3820 date_format: str | None = ...,
3821 doublequote: bool = ...,
3822 escapechar: str | None = ...,
3823 decimal: str = ...,
3824 errors: OpenFileErrors = ...,
3825 storage_options: StorageOptions = ...,
3826 ) -> None: ...
3828 @final
3829 def to_csv(
3830 self,
3831 path_or_buf: FilePath | WriteBuffer[bytes] | WriteBuffer[str] | None = None,
3832 *,
3833 sep: str = ",",
3834 na_rep: str = "",
3835 float_format: str | Callable | None = None,
3836 columns: Sequence[Hashable] | None = None,
3837 header: bool | list[str] = True,
3838 index: bool = True,
3839 index_label: IndexLabel | None = None,
3840 mode: str = "w",
3841 encoding: str | None = None,
3842 compression: CompressionOptions = "infer",
3843 quoting: int | None = None,
3844 quotechar: str = '"',
3845 lineterminator: str | None = None,
3846 chunksize: int | None = None,
3847 date_format: str | None = None,
3848 doublequote: bool = True,
3849 escapechar: str | None = None,
3850 decimal: str = ".",
3851 errors: OpenFileErrors = "strict",
3852 storage_options: StorageOptions | None = None,
3853 ) -> str | None:
3854 r"""
3855 Write object to a comma-separated values (csv) file.
3857 By default, the resulting file includes row index and column headers.
3858 Supports customization of delimiter, encoding, compression, and more.
3859 The output can be written to a file path, file-like buffer, or
3860 returned as a string.
3862 Parameters
3863 ----------
3864 path_or_buf : str, path object, file-like object, or None, default None
3865 String, path object (implementing os.PathLike[str]), or file-like
3866 object implementing a write() function. If None, the result is
3867 returned as a string. If a non-binary file object is passed, it should
3868 be opened with `newline=''`, disabling universal newlines. If a binary
3869 file object is passed, `mode` might need to contain a `'b'`.
3870 sep : str, default ','
3871 String of length 1. Field delimiter for the output file.
3872 na_rep : str, default ''
3873 Missing data representation.
3874 float_format : str, Callable, default None
3875 Format string for floating point numbers. If a Callable is given, it takes
3876 precedence over other numeric formatting parameters, like decimal.
3877 columns : sequence, optional
3878 Columns to write.
3879 header : bool or list of str, default True
3880 Write out the column names. If a list of strings is given it is
3881 assumed to be aliases for the column names.
3882 index : bool, default True
3883 Write row names (index).
3884 index_label : str or sequence, or False, default None
3885 Column label for index column(s) if desired. If None is given, and
3886 `header` and `index` are True, then the index names are used. A
3887 sequence should be given if the object uses MultiIndex. If
3888 False do not print fields for index names. Use index_label=False
3889 for easier importing in R.
3890 mode : {'w', 'x', 'a'}, default 'w'
3891 Forwarded to either `open(mode=)` or `fsspec.open(mode=)` to control
3892 the file opening. Typical values include:
3894 - 'w', truncate the file first.
3895 - 'x', exclusive creation, failing if the file already exists.
3896 - 'a', append to the end of file if it exists.
3898 encoding : str, optional
3899 A string representing the encoding to use in the output file,
3900 defaults to 'utf-8'. `encoding` is not supported if `path_or_buf`
3901 is a non-binary file object.
3903 compression : str or dict, default 'infer'
3904 For on-the-fly compression of the output data. If 'infer' and
3905 'path_or_buf' is path-like, then detect compression from the following
3906 extensions: '.gz',
3907 '.bz2', '.zip', '.xz', '.zst', '.tar', '.tar.gz', '.tar.xz' or '.tar.bz2'
3908 (otherwise no compression).
3909 Set to ``None`` for no compression.
3910 Can also be a dict with key ``'method'`` set to one of
3911 {``'zip'``, ``'gzip'``, ``'bz2'``, ``'zstd'``, ``'xz'``, ``'tar'``} and
3912 other key-value pairs are forwarded to
3913 ``zipfile.ZipFile``, ``gzip.GzipFile``,
3914 ``bz2.BZ2File``, ``zstandard.ZstdCompressor``, ``lzma.LZMAFile`` or
3915 ``tarfile.TarFile``, respectively.
3916 As an example, the following could be passed for faster compression and
3917 to create a reproducible gzip archive:
3918 ``compression={'method': 'gzip', 'compresslevel': 1, 'mtime': 1}``.
3920 May be a dict with key 'method' as compression mode
3921 and other entries as additional compression options if
3922 compression mode is 'zip'.
3924 Passing compression options as keys in dict is
3925 supported for compression modes 'gzip', 'bz2', 'zstd', and 'zip'.
3926 quoting : optional constant from csv module
3927 Defaults to csv.QUOTE_MINIMAL. If you have set a `float_format`
3928 then floats are converted to strings and thus csv.QUOTE_NONNUMERIC
3929 will treat them as non-numeric.
3930 quotechar : str, default '\"'
3931 String of length 1. Character used to quote fields.
3932 lineterminator : str, optional
3933 The newline character or character sequence to use in the output
3934 file. Defaults to `os.linesep`, which depends on the OS in which
3935 this method is called ('\\n' for linux, '\\r\\n' for Windows, i.e.).
3936 chunksize : int or None
3937 Rows to write at a time.
3938 date_format : str, default None
3939 Format string for datetime objects.
3940 doublequote : bool, default True
3941 Control quoting of `quotechar` inside a field.
3942 escapechar : str, default None
3943 String of length 1. Character used to escape `sep` and `quotechar`
3944 when appropriate.
3945 decimal : str, default '.'
3946 Character recognized as decimal separator. E.g. use ',' for
3947 European data.
3948 errors : str, default 'strict'
3949 Specifies how encoding and decoding errors are to be handled.
3950 See the errors argument for :func:`open` for a full list
3951 of options.
3953 storage_options : dict, optional
3954 Extra options that make sense for a particular storage connection, e.g.
3955 host, port, username, password, etc. For HTTP(S) URLs the key-value pairs
3956 are forwarded to ``urllib.request.Request`` as header options. For other
3957 URLs (e.g. starting with "s3://", and "gcs://") the key-value pairs are
3958 forwarded to ``fsspec.open``. Please see ``fsspec`` and ``urllib`` for more
3959 details, and for more examples on storage options refer `here
3960 <https://pandas.pydata.org/docs/user_guide/io.html?
3961 highlight=storage_options#reading-writing-remote-files>`_.
3963 Returns
3964 -------
3965 None or str
3966 If path_or_buf is None, returns the resulting csv format as a
3967 string. Otherwise returns None.
3969 See Also
3970 --------
3971 read_csv : Load a CSV file into a DataFrame.
3972 to_excel : Write DataFrame to an Excel file.
3974 Examples
3975 --------
3976 Create 'out.csv' containing 'df' without indices
3978 >>> df = pd.DataFrame(
3979 ... [["Raphael", "red", "sai"], ["Donatello", "purple", "bo staff"]],
3980 ... columns=["name", "mask", "weapon"],
3981 ... )
3982 >>> df.to_csv("out.csv", index=False) # doctest: +SKIP
3984 Create 'out.zip' containing 'out.csv'
3986 >>> df.to_csv(index=False)
3987 'name,mask,weapon\nRaphael,red,sai\nDonatello,purple,bo staff\n'
3988 >>> compression_opts = dict(
3989 ... method="zip", archive_name="out.csv"
3990 ... ) # doctest: +SKIP
3991 >>> df.to_csv(
3992 ... "out.zip", index=False, compression=compression_opts
3993 ... ) # doctest: +SKIP
3995 To write a csv file to a new folder or nested folder you will first
3996 need to create it using either Pathlib or os:
3998 >>> from pathlib import Path # doctest: +SKIP
3999 >>> filepath = Path("folder/subfolder/out.csv") # doctest: +SKIP
4000 >>> filepath.parent.mkdir(parents=True, exist_ok=True) # doctest: +SKIP
4001 >>> df.to_csv(filepath) # doctest: +SKIP
4003 >>> import os # doctest: +SKIP
4004 >>> os.makedirs("folder/subfolder", exist_ok=True) # doctest: +SKIP
4005 >>> df.to_csv("folder/subfolder/out.csv") # doctest: +SKIP
4007 Format floats to two decimal places:
4009 >>> df.to_csv("out1.csv", float_format="%.2f") # doctest: +SKIP
4011 Format floats using scientific notation:
4013 >>> df.to_csv("out2.csv", float_format="{:.2e}".format) # doctest: +SKIP
4014 """
4015 df = self if isinstance(self, ABCDataFrame) else self.to_frame()
4017 formatter = DataFrameFormatter(
4018 frame=df,
4019 header=header,
4020 index=index,
4021 na_rep=na_rep,
4022 float_format=float_format,
4023 decimal=decimal,
4024 )
4026 return DataFrameRenderer(formatter).to_csv(
4027 path_or_buf,
4028 lineterminator=lineterminator,
4029 sep=sep,
4030 encoding=encoding,
4031 errors=errors,
4032 compression=compression,
4033 quoting=quoting,
4034 columns=columns,
4035 index_label=index_label,
4036 mode=mode,
4037 chunksize=chunksize,
4038 quotechar=quotechar,
4039 date_format=date_format,
4040 doublequote=doublequote,
4041 escapechar=escapechar,
4042 storage_options=storage_options,
4043 )
4045 # ----------------------------------------------------------------------
4046 # Indexing Methods
4048 @final
4049 def take(self, indices, axis: Axis = 0, **kwargs) -> Self:
4050 """
4051 Return the elements in the given *positional* indices along an axis.
4053 This means that we are not indexing according to actual values in
4054 the index attribute of the object. We are indexing according to the
4055 actual position of the element in the object.
4057 Parameters
4058 ----------
4059 indices : array-like
4060 An array of ints indicating which positions to take.
4061 axis : {0 or 'index', 1 or 'columns'}, default 0
4062 The axis on which to select elements. ``0`` means that we are
4063 selecting rows, ``1`` means that we are selecting columns.
4064 For `Series` this parameter is unused and defaults to 0.
4065 **kwargs
4066 For compatibility with :meth:`numpy.take`. Has no effect on the
4067 output.
4069 Returns
4070 -------
4071 same type as caller
4072 An array-like containing the elements taken from the object.
4074 See Also
4075 --------
4076 DataFrame.loc : Select a subset of a DataFrame by labels.
4077 DataFrame.iloc : Select a subset of a DataFrame by positions.
4078 numpy.take : Take elements from an array along an axis.
4080 Examples
4081 --------
4082 >>> df = pd.DataFrame(
4083 ... [
4084 ... ("falcon", "bird", 389.0),
4085 ... ("parrot", "bird", 24.0),
4086 ... ("lion", "mammal", 80.5),
4087 ... ("monkey", "mammal", np.nan),
4088 ... ],
4089 ... columns=["name", "class", "max_speed"],
4090 ... index=[0, 2, 3, 1],
4091 ... )
4092 >>> df
4093 name class max_speed
4094 0 falcon bird 389.0
4095 2 parrot bird 24.0
4096 3 lion mammal 80.5
4097 1 monkey mammal NaN
4099 Take elements at positions 0 and 3 along the axis 0 (default).
4101 Note how the actual indices selected (0 and 1) do not correspond to
4102 our selected indices 0 and 3. That's because we are selecting the 0th
4103 and 3rd rows, not rows whose indices equal 0 and 3.
4105 >>> df.take([0, 3])
4106 name class max_speed
4107 0 falcon bird 389.0
4108 1 monkey mammal NaN
4110 Take elements at indices 1 and 2 along the axis 1 (column selection).
4112 >>> df.take([1, 2], axis=1)
4113 class max_speed
4114 0 bird 389.0
4115 2 bird 24.0
4116 3 mammal 80.5
4117 1 mammal NaN
4119 We may take elements using negative integers for positive indices,
4120 starting from the end of the object, just like with Python lists.
4122 >>> df.take([-1, -2])
4123 name class max_speed
4124 1 monkey mammal NaN
4125 3 lion mammal 80.5
4126 """
4128 nv.validate_take((), kwargs)
4130 if isinstance(indices, slice):
4131 raise TypeError(
4132 f"{type(self).__name__}.take requires a sequence of integers, "
4133 "not slice."
4134 )
4135 indices = np.asarray(indices, dtype=np.intp)
4136 if axis == 0 and indices.ndim == 1 and is_range_indexer(indices, len(self)):
4137 return self.copy(deep=False)
4139 new_data = self._mgr.take(
4140 indices,
4141 axis=self._get_block_manager_axis(axis),
4142 verify=True,
4143 )
4144 return self._constructor_from_mgr(new_data, axes=new_data.axes).__finalize__(
4145 self, method="take"
4146 )
4148 @final
4149 def xs(
4150 self,
4151 key: IndexLabel,
4152 axis: Axis = 0,
4153 level: IndexLabel | None = None,
4154 drop_level: bool = True,
4155 ) -> Self:
4156 """
4157 Return cross-section from the Series/DataFrame.
4159 This method takes a `key` argument to select data at a particular
4160 level of a MultiIndex.
4162 Parameters
4163 ----------
4164 key : label or tuple of label
4165 Label contained in the index, or partially in a MultiIndex.
4166 axis : {0 or 'index', 1 or 'columns'}, default 0
4167 Axis to retrieve cross-section on.
4168 level : object, defaults to first n levels (n=1 or len(key))
4169 In case of a key partially contained in a MultiIndex, indicate
4170 which levels are used. Levels can be referred by label or position.
4171 drop_level : bool, default True
4172 If False, returns object with same levels as self.
4174 Returns
4175 -------
4176 Series or DataFrame
4177 Cross-section from the original Series or DataFrame
4178 corresponding to the selected index levels.
4180 See Also
4181 --------
4182 DataFrame.loc : Access a group of rows and columns
4183 by label(s) or a boolean array.
4184 DataFrame.iloc : Purely integer-location based indexing
4185 for selection by position.
4187 Notes
4188 -----
4189 `xs` can not be used to set values.
4191 MultiIndex Slicers is a generic way to get/set values on
4192 any level or levels.
4193 It is a superset of `xs` functionality, see
4194 :ref:`MultiIndex Slicers <advanced.mi_slicers>`.
4196 Examples
4197 --------
4198 >>> d = {
4199 ... "num_legs": [4, 4, 2, 2],
4200 ... "num_wings": [0, 0, 2, 2],
4201 ... "class": ["mammal", "mammal", "mammal", "bird"],
4202 ... "animal": ["cat", "dog", "bat", "penguin"],
4203 ... "locomotion": ["walks", "walks", "flies", "walks"],
4204 ... }
4205 >>> df = pd.DataFrame(data=d)
4206 >>> df = df.set_index(["class", "animal", "locomotion"])
4207 >>> df
4208 num_legs num_wings
4209 class animal locomotion
4210 mammal cat walks 4 0
4211 dog walks 4 0
4212 bat flies 2 2
4213 bird penguin walks 2 2
4215 Get values at specified index
4217 >>> df.xs("mammal")
4218 num_legs num_wings
4219 animal locomotion
4220 cat walks 4 0
4221 dog walks 4 0
4222 bat flies 2 2
4224 Get values at several indexes
4226 >>> df.xs(("mammal", "dog", "walks"))
4227 num_legs 4
4228 num_wings 0
4229 Name: (mammal, dog, walks), dtype: int64
4231 Get values at specified index and level
4233 >>> df.xs("cat", level=1)
4234 num_legs num_wings
4235 class locomotion
4236 mammal walks 4 0
4238 Get values at several indexes and levels
4240 >>> df.xs(("bird", "walks"), level=[0, "locomotion"])
4241 num_legs num_wings
4242 animal
4243 penguin 2 2
4245 Get values at specified column and axis
4247 >>> df.xs("num_wings", axis=1)
4248 class animal locomotion
4249 mammal cat walks 0
4250 dog walks 0
4251 bat flies 2
4252 bird penguin walks 2
4253 Name: num_wings, dtype: int64
4254 """
4255 axis = self._get_axis_number(axis)
4256 labels = self._get_axis(axis)
4258 if isinstance(key, list):
4259 raise TypeError("list keys are not supported in xs, pass a tuple instead")
4261 if level is not None:
4262 if not isinstance(labels, MultiIndex):
4263 raise TypeError("Index must be a MultiIndex")
4264 loc, new_ax = labels.get_loc_level(key, level=level, drop_level=drop_level)
4266 # create the tuple of the indexer
4267 _indexer = [slice(None)] * self.ndim
4268 _indexer[axis] = loc
4269 indexer = tuple(_indexer)
4271 result = self.iloc[indexer]
4272 setattr(result, result._get_axis_name(axis), new_ax)
4273 return result
4275 if axis == 1:
4276 if drop_level:
4277 return self[key]
4278 index = self.columns
4279 else:
4280 index = self.index
4282 if isinstance(index, MultiIndex):
4283 loc, new_index = index._get_loc_level(key, level=0)
4284 if not drop_level:
4285 if lib.is_integer(loc):
4286 # Slice index must be an integer or None
4287 new_index = index[loc : loc + 1]
4288 else:
4289 new_index = index[loc]
4290 else:
4291 loc = index.get_loc(key)
4293 if isinstance(loc, np.ndarray):
4294 if loc.dtype == np.bool_:
4295 (inds,) = loc.nonzero()
4296 return self.take(inds, axis=axis)
4297 else:
4298 return self.take(loc, axis=axis)
4300 if not is_scalar(loc):
4301 new_index = index[loc]
4303 if is_scalar(loc) and axis == 0:
4304 # In this case loc should be an integer
4305 if self.ndim == 1:
4306 # if we encounter an array-like and we only have 1 dim
4307 # that means that their are list/ndarrays inside the Series!
4308 # so just return them (GH 6394)
4309 return self._ixs(loc, axis=0)
4311 if not drop_level and isinstance(index, MultiIndex):
4312 # GH#6507 - honor drop_level=False for fully specified keys
4313 result = self.iloc[loc : loc + 1]
4314 result.index = new_index
4315 return result
4317 result = self._ixs(loc, axis=0)
4318 elif is_scalar(loc):
4319 result = self.iloc[:, slice(loc, loc + 1)]
4320 elif axis == 1:
4321 result = self.iloc[:, loc]
4322 elif isinstance(loc, slice):
4323 # GH#38650: bypass iloc dispatch and pass new_index
4324 # directly to avoid redundantly slicing the index
4325 # in the manager path.
4326 result = self._slice(loc, new_index=new_index)
4327 else:
4328 result = self.iloc[loc]
4329 result.index = new_index
4331 return result
4333 def __getitem__(self, item):
4334 raise AbstractMethodError(self)
4336 @final
4337 def _getitem_slice(self, key: slice) -> Self:
4338 """
4339 __getitem__ for the case where the key is a slice object.
4340 """
4341 # _convert_slice_indexer to determine if this slice is positional
4342 # or label based, and if the latter, convert to positional
4343 slobj = self.index._convert_slice_indexer(key, kind="getitem")
4344 if isinstance(slobj, np.ndarray):
4345 # reachable with DatetimeIndex
4346 indexer = lib.maybe_indices_to_slice(slobj.astype(np.intp), len(self))
4347 if isinstance(indexer, np.ndarray):
4348 # GH#43223 If we can not convert, use take
4349 return self.take(indexer, axis=0)
4350 slobj = indexer
4351 return self._slice(slobj)
4353 def _slice(
4354 self, slobj: slice, axis: AxisInt = 0, new_index: Index | None = None
4355 ) -> Self:
4356 """
4357 Construct a slice of this container.
4359 Slicing with this method is *always* positional.
4360 """
4361 assert isinstance(slobj, slice), type(slobj)
4362 axis = self._get_block_manager_axis(axis)
4363 new_mgr = self._mgr.get_slice(slobj, axis=axis, new_index=new_index)
4364 result = self._constructor_from_mgr(new_mgr, axes=new_mgr.axes)
4365 result = result.__finalize__(self)
4366 return result
4368 @final
4369 def __delitem__(self, key) -> None:
4370 """
4371 Delete item
4372 """
4373 deleted = False
4375 maybe_shortcut = False
4376 if self.ndim == 2 and isinstance(self.columns, MultiIndex):
4377 try:
4378 # By using engine's __contains__ we effectively
4379 # restrict to same-length tuples
4380 maybe_shortcut = key not in self.columns._engine
4381 except TypeError:
4382 pass
4384 if maybe_shortcut:
4385 # Allow shorthand to delete all columns whose first len(key)
4386 # elements match key:
4387 if not isinstance(key, tuple):
4388 key = (key,)
4389 for col in self.columns:
4390 if isinstance(col, tuple) and col[: len(key)] == key:
4391 del self[col]
4392 deleted = True
4393 if not deleted:
4394 # If the above loop ran and didn't delete anything because
4395 # there was no match, this call should raise the appropriate
4396 # exception:
4397 loc = self.axes[-1].get_loc(key)
4398 self._mgr = self._mgr.idelete(loc)
4400 # ----------------------------------------------------------------------
4401 # Unsorted
4403 @final
4404 def _check_inplace_and_allows_duplicate_labels(self, inplace: bool) -> None:
4405 if inplace and not self.flags.allows_duplicate_labels:
4406 raise ValueError(
4407 "Cannot specify 'inplace=True' when "
4408 "'self.flags.allows_duplicate_labels' is False."
4409 )
4411 @final
4412 def get(self, key, default=None):
4413 """
4414 Get item from object for given key (ex: DataFrame column).
4416 Returns ``default`` value if not found.
4418 Parameters
4419 ----------
4420 key : object
4421 Key for which item should be returned.
4422 default : object, default None
4423 Default value to return if key is not found.
4425 Returns
4426 -------
4427 same type as items contained in object
4428 Item for given key or ``default`` value, if key is not found.
4430 See Also
4431 --------
4432 DataFrame.get : Get item from object for given key (ex: DataFrame column).
4433 Series.get : Get item from object for given key (ex: DataFrame column).
4435 Examples
4436 --------
4437 >>> df = pd.DataFrame(
4438 ... [
4439 ... [24.3, 75.7, "high"],
4440 ... [31, 87.8, "high"],
4441 ... [22, 71.6, "medium"],
4442 ... [35, 95, "medium"],
4443 ... ],
4444 ... columns=["temp_celsius", "temp_fahrenheit", "windspeed"],
4445 ... index=pd.date_range(start="2014-02-12", end="2014-02-15", freq="D"),
4446 ... )
4448 >>> df
4449 temp_celsius temp_fahrenheit windspeed
4450 2014-02-12 24.3 75.7 high
4451 2014-02-13 31.0 87.8 high
4452 2014-02-14 22.0 71.6 medium
4453 2014-02-15 35.0 95.0 medium
4455 >>> df.get(["temp_celsius", "windspeed"])
4456 temp_celsius windspeed
4457 2014-02-12 24.3 high
4458 2014-02-13 31.0 high
4459 2014-02-14 22.0 medium
4460 2014-02-15 35.0 medium
4462 >>> ser = df["windspeed"]
4463 >>> ser.get("2014-02-13")
4464 'high'
4466 If the key isn't found, the default value will be used.
4468 >>> df.get(["temp_celsius", "temp_kelvin"], default="default_value")
4469 'default_value'
4471 >>> ser.get("2014-02-10", "[unknown]")
4472 '[unknown]'
4474 When passing a list of keys, all keys must be present. If any key
4475 is missing, the ``default`` value is returned instead of a partial result.
4477 >>> ser = pd.Series(["a", "b", "c"], index=[1, 2, 3])
4478 >>> ser.get([1, 2])
4479 1 a
4480 2 b
4481 dtype: str
4482 >>> ser.get([1, 2, -1]) is None
4483 True
4484 """
4485 try:
4486 return self[key]
4487 except (KeyError, ValueError, IndexError):
4488 return default
4490 @staticmethod
4491 def _check_copy_deprecation(copy):
4492 if copy is not lib.no_default:
4493 warnings.warn(
4494 "The copy keyword is deprecated and will be removed in a future "
4495 "version. Copy-on-Write is active in pandas since 3.0 which utilizes "
4496 "a lazy copy mechanism that defers copies until necessary. Use "
4497 ".copy() to make an eager copy if necessary.",
4498 Pandas4Warning,
4499 stacklevel=find_stack_level(),
4500 )
4502 def _check_inplace_deprecation(
4503 self, inplace: bool | lib.NoDefault, method: str
4504 ) -> bool:
4505 if inplace is not lib.no_default:
4506 # GH#63207
4507 warnings.warn(
4508 f"The inplace keyword in {type(self).__name__}.{method} is "
4509 "deprecated and will be removed in a future version (PDEP-8).\n"
4510 "See "
4511 "https://pandas.pydata.org/docs/dev/whatsnew/v3.1.0.html#deprecation-inplace"
4512 " for more details.",
4513 Pandas4Warning,
4514 stacklevel=3,
4515 )
4516 else:
4517 inplace = False
4519 return inplace
4521 # issue 58667
4522 @deprecate_kwarg(Pandas4Warning, "method", new_arg_name=None)
4523 @final
4524 def reindex_like(
4525 self,
4526 other,
4527 method: Literal["backfill", "bfill", "pad", "ffill", "nearest"] | None = None,
4528 copy: bool | lib.NoDefault = lib.no_default,
4529 limit: int | None = None,
4530 tolerance=None,
4531 ) -> Self:
4532 """
4533 Return an object with matching indices as other object.
4535 Conform the object to the same index on all axes. Optional
4536 filling logic, placing NaN in locations having no value
4537 in the previous index. A new object is produced unless the
4538 new index is equivalent to the current one and copy=False.
4540 Parameters
4541 ----------
4542 other : Object of the same data type
4543 Its row and column indices are used to define the new indices
4544 of this object.
4545 method : {None, 'backfill'/'bfill', 'pad'/'ffill', 'nearest'}
4546 Method to use for filling holes in reindexed DataFrame.
4547 Please note: this is only applicable to DataFrames/Series with a
4548 monotonically increasing/decreasing index.
4550 .. deprecated:: 3.0.0
4552 * None (default): don't fill gaps
4553 * pad / ffill: propagate last valid observation forward to next
4554 valid
4555 * backfill / bfill: use next valid observation to fill gap
4556 * nearest: use nearest valid observations to fill gap.
4558 copy : bool, default False
4559 This keyword is now ignored; changing its value will have no
4560 impact on the method.
4562 .. deprecated:: 3.0.0
4564 This keyword is ignored and will be removed in pandas 4.0. Since
4565 pandas 3.0, this method always returns a new object using a lazy
4566 copy mechanism that defers copies until necessary
4567 (Copy-on-Write). See the `user guide on Copy-on-Write
4568 <https://pandas.pydata.org/docs/dev/user_guide/migration.html>`__
4569 for more details.
4571 limit : int, default None
4572 Maximum number of consecutive labels to fill for inexact matches.
4573 tolerance : optional
4574 Maximum distance between original and new labels for inexact
4575 matches. The values of the index at the matching locations must
4576 satisfy the equation ``abs(index[indexer] - target) <= tolerance``.
4578 Tolerance may be a scalar value, which applies the same tolerance
4579 to all values, or list-like, which applies variable tolerance per
4580 element. List-like includes list, tuple, array, Series, and must be
4581 the same size as the index and its dtype must exactly match the
4582 index's type.
4584 Returns
4585 -------
4586 Series or DataFrame
4587 Same type as caller, but with changed indices on each axis.
4589 See Also
4590 --------
4591 DataFrame.set_index : Set row labels.
4592 DataFrame.reset_index : Remove row labels or move them to new columns.
4593 DataFrame.reindex : Change to new indices or expand indices.
4595 Notes
4596 -----
4597 Same as calling
4598 ``.reindex(index=other.index, columns=other.columns,...)``.
4600 Examples
4601 --------
4602 >>> df1 = pd.DataFrame(
4603 ... [
4604 ... [24.3, 75.7, "high"],
4605 ... [31, 87.8, "high"],
4606 ... [22, 71.6, "medium"],
4607 ... [35, 95, "medium"],
4608 ... ],
4609 ... columns=["temp_celsius", "temp_fahrenheit", "windspeed"],
4610 ... index=pd.date_range(start="2014-02-12", end="2014-02-15", freq="D"),
4611 ... )
4613 >>> df1
4614 temp_celsius temp_fahrenheit windspeed
4615 2014-02-12 24.3 75.7 high
4616 2014-02-13 31.0 87.8 high
4617 2014-02-14 22.0 71.6 medium
4618 2014-02-15 35.0 95.0 medium
4620 >>> df2 = pd.DataFrame(
4621 ... [[28, "low"], [30, "low"], [35.1, "medium"]],
4622 ... columns=["temp_celsius", "windspeed"],
4623 ... index=pd.DatetimeIndex(["2014-02-12", "2014-02-13", "2014-02-15"]),
4624 ... )
4626 >>> df2
4627 temp_celsius windspeed
4628 2014-02-12 28.0 low
4629 2014-02-13 30.0 low
4630 2014-02-15 35.1 medium
4632 >>> df2.reindex_like(df1)
4633 temp_celsius temp_fahrenheit windspeed
4634 2014-02-12 28.0 NaN low
4635 2014-02-13 30.0 NaN low
4636 2014-02-14 NaN NaN NaN
4637 2014-02-15 35.1 NaN medium
4638 """
4639 self._check_copy_deprecation(copy)
4640 d = other._construct_axes_dict(
4641 axes=self._AXIS_ORDERS,
4642 method=method,
4643 limit=limit,
4644 tolerance=tolerance,
4645 )
4647 return self.reindex(**d)
4649 @overload
4650 def drop(
4651 self,
4652 labels: IndexLabel | ListLike = ...,
4653 *,
4654 axis: Axis = ...,
4655 index: IndexLabel | ListLike = ...,
4656 columns: IndexLabel | ListLike = ...,
4657 level: Level | None = ...,
4658 inplace: Literal[True],
4659 errors: IgnoreRaise = ...,
4660 ) -> None: ...
4662 @overload
4663 def drop(
4664 self,
4665 labels: IndexLabel | ListLike = ...,
4666 *,
4667 axis: Axis = ...,
4668 index: IndexLabel | ListLike = ...,
4669 columns: IndexLabel | ListLike = ...,
4670 level: Level | None = ...,
4671 inplace: Literal[False] = ...,
4672 errors: IgnoreRaise = ...,
4673 ) -> Self: ...
4675 @overload
4676 def drop(
4677 self,
4678 labels: IndexLabel | ListLike = ...,
4679 *,
4680 axis: Axis = ...,
4681 index: IndexLabel | ListLike = ...,
4682 columns: IndexLabel | ListLike = ...,
4683 level: Level | None = ...,
4684 inplace: bool = ...,
4685 errors: IgnoreRaise = ...,
4686 ) -> Self | None: ...
4688 def drop(
4689 self,
4690 labels: IndexLabel | ListLike = None,
4691 *,
4692 axis: Axis = 0,
4693 index: IndexLabel | ListLike = None,
4694 columns: IndexLabel | ListLike = None,
4695 level: Level | None = None,
4696 inplace: bool = False,
4697 errors: IgnoreRaise = "raise",
4698 ) -> Self | None:
4699 inplace = validate_bool_kwarg(inplace, "inplace")
4701 if labels is not None:
4702 if index is not None or columns is not None:
4703 raise ValueError("Cannot specify both 'labels' and 'index'/'columns'")
4704 axis_name = self._get_axis_name(axis)
4705 axes = {axis_name: labels}
4706 elif index is not None or columns is not None:
4707 if axis == 1:
4708 raise ValueError("Cannot specify both 'axis' and 'index'/'columns'")
4709 axes = {"index": index}
4710 if self.ndim == 2:
4711 axes["columns"] = columns
4712 else:
4713 raise ValueError(
4714 "Need to specify at least one of 'labels', 'index' or 'columns'"
4715 )
4717 obj = self
4719 for axis, labels in axes.items():
4720 if labels is not None:
4721 obj = obj._drop_axis(labels, axis, level=level, errors=errors)
4723 if inplace:
4724 self._update_inplace(obj)
4725 return None
4726 else:
4727 return obj
4729 @final
4730 def _drop_axis(
4731 self,
4732 labels,
4733 axis,
4734 level=None,
4735 errors: IgnoreRaise = "raise",
4736 ) -> Self:
4737 """
4738 Drop labels from specified axis. Used in the ``drop`` method
4739 internally.
4741 Parameters
4742 ----------
4743 labels : single label or list-like
4744 axis : int or axis name
4745 level : int or level name, default None
4746 For MultiIndex
4747 errors : {'ignore', 'raise'}, default 'raise'
4748 If 'ignore', suppress error and existing labels are dropped.
4750 """
4751 axis_num = self._get_axis_number(axis)
4752 axis = self._get_axis(axis)
4754 if axis.is_unique:
4755 if level is not None:
4756 if not isinstance(axis, MultiIndex):
4757 raise AssertionError("axis must be a MultiIndex")
4758 new_axis = axis.drop(labels, level=level, errors=errors)
4759 else:
4760 new_axis = axis.drop(labels, errors=errors)
4761 indexer = axis.get_indexer(new_axis)
4763 # Case for non-unique axis
4764 else:
4765 is_tuple_labels = is_nested_list_like(labels) or isinstance(labels, tuple)
4766 labels = ensure_object(common.index_labels_to_array(labels))
4767 if level is not None:
4768 if not isinstance(axis, MultiIndex):
4769 raise AssertionError("axis must be a MultiIndex")
4770 mask = ~axis.get_level_values(level).isin(labels)
4772 # GH 18561 MultiIndex.drop should raise if label is absent
4773 if errors == "raise" and mask.all():
4774 raise KeyError(f"{labels} not found in axis")
4775 elif (
4776 isinstance(axis, MultiIndex)
4777 and labels.dtype == "object"
4778 and not is_tuple_labels
4779 ):
4780 # Set level to zero in case of MultiIndex and label is string,
4781 # because isin can't handle strings for MultiIndexes GH#36293
4782 # In case of tuples we get dtype object but have to use isin GH#42771
4783 mask = ~axis.get_level_values(0).isin(labels)
4784 else:
4785 mask = ~axis.isin(labels)
4786 # Check if label doesn't exist along axis
4787 labels_missing = (axis.get_indexer_for(labels) == -1).any()
4788 if errors == "raise" and labels_missing:
4789 raise KeyError(f"{labels} not found in axis")
4791 if isinstance(mask.dtype, ExtensionDtype):
4792 # GH#45860
4793 mask = mask.to_numpy(dtype=bool)
4795 indexer = mask.nonzero()[0]
4796 new_axis = axis.take(indexer)
4798 bm_axis = self.ndim - axis_num - 1
4799 new_mgr = self._mgr.reindex_indexer(
4800 new_axis,
4801 indexer,
4802 axis=bm_axis,
4803 allow_dups=True,
4804 only_slice=True,
4805 )
4806 result = self._constructor_from_mgr(new_mgr, axes=new_mgr.axes)
4807 if self.ndim == 1:
4808 result._name = self.name
4810 return result.__finalize__(self)
4812 @final
4813 def _update_inplace(self, result) -> None:
4814 """
4815 Replace self internals with result.
4817 Parameters
4818 ----------
4819 result : same type as self
4820 """
4821 # NOTE: This does *not* call __finalize__ and that's an explicit
4822 # decision that we may revisit in the future.
4823 self._mgr = result._mgr
4825 @final
4826 def add_prefix(self, prefix: str, axis: Axis | None = None) -> Self:
4827 """
4828 Prefix labels with string `prefix`.
4830 For Series, the row labels are prefixed.
4831 For DataFrame, the column labels are prefixed.
4833 Parameters
4834 ----------
4835 prefix : str
4836 The string to add before each label.
4837 axis : {0 or 'index', 1 or 'columns', None}, default None
4838 Axis to add prefix on
4840 .. versionadded:: 2.0.0
4842 Returns
4843 -------
4844 Series or DataFrame
4845 New Series or DataFrame with updated labels.
4847 See Also
4848 --------
4849 Series.add_suffix: Suffix row labels with string `suffix`.
4850 DataFrame.add_suffix: Suffix column labels with string `suffix`.
4852 Examples
4853 --------
4854 >>> s = pd.Series([1, 2, 3, 4])
4855 >>> s
4856 0 1
4857 1 2
4858 2 3
4859 3 4
4860 dtype: int64
4862 >>> s.add_prefix("item_")
4863 item_0 1
4864 item_1 2
4865 item_2 3
4866 item_3 4
4867 dtype: int64
4869 >>> df = pd.DataFrame({"A": [1, 2, 3, 4], "B": [3, 4, 5, 6]})
4870 >>> df
4871 A B
4872 0 1 3
4873 1 2 4
4874 2 3 5
4875 3 4 6
4877 >>> df.add_prefix("col_")
4878 col_A col_B
4879 0 1 3
4880 1 2 4
4881 2 3 5
4882 3 4 6
4883 """
4884 f = lambda x: f"{prefix}{x}"
4886 axis_name = self._info_axis_name
4887 if axis is not None:
4888 axis_name = self._get_axis_name(axis)
4890 mapper = {axis_name: f}
4892 # error: Keywords must be strings
4893 # error: No overload variant of "_rename" of "NDFrame" matches
4894 # argument type "dict[Literal['index', 'columns'], Callable[[Any], str]]"
4895 return self._rename(**mapper) # type: ignore[call-overload]
4897 @final
4898 def add_suffix(self, suffix: str, axis: Axis | None = None) -> Self:
4899 """
4900 Suffix labels with string `suffix`.
4902 For Series, the row labels are suffixed.
4903 For DataFrame, the column labels are suffixed.
4905 Parameters
4906 ----------
4907 suffix : str
4908 The string to add after each label.
4909 axis : {0 or 'index', 1 or 'columns', None}, default None
4910 Axis to add suffix on
4912 .. versionadded:: 2.0.0
4914 Returns
4915 -------
4916 Series or DataFrame
4917 New Series or DataFrame with updated labels.
4919 See Also
4920 --------
4921 Series.add_prefix: Prefix row labels with string `prefix`.
4922 DataFrame.add_prefix: Prefix column labels with string `prefix`.
4924 Examples
4925 --------
4926 >>> s = pd.Series([1, 2, 3, 4])
4927 >>> s
4928 0 1
4929 1 2
4930 2 3
4931 3 4
4932 dtype: int64
4934 >>> s.add_suffix("_item")
4935 0_item 1
4936 1_item 2
4937 2_item 3
4938 3_item 4
4939 dtype: int64
4941 >>> df = pd.DataFrame({"A": [1, 2, 3, 4], "B": [3, 4, 5, 6]})
4942 >>> df
4943 A B
4944 0 1 3
4945 1 2 4
4946 2 3 5
4947 3 4 6
4949 >>> df.add_suffix("_col")
4950 A_col B_col
4951 0 1 3
4952 1 2 4
4953 2 3 5
4954 3 4 6
4955 """
4956 f = lambda x: f"{x}{suffix}"
4958 axis_name = self._info_axis_name
4959 if axis is not None:
4960 axis_name = self._get_axis_name(axis)
4962 mapper = {axis_name: f}
4963 # error: Keywords must be strings
4964 # error: No overload variant of "_rename" of "NDFrame" matches argument
4965 # type "dict[Literal['index', 'columns'], Callable[[Any], str]]"
4966 return self._rename(**mapper) # type: ignore[call-overload]
4968 @overload
4969 def sort_values(
4970 self,
4971 *,
4972 axis: Axis = ...,
4973 ascending: bool | Sequence[bool] = ...,
4974 inplace: Literal[False] = ...,
4975 kind: SortKind = ...,
4976 na_position: NaPosition = ...,
4977 ignore_index: bool = ...,
4978 key: ValueKeyFunc = ...,
4979 ) -> Self: ...
4981 @overload
4982 def sort_values(
4983 self,
4984 *,
4985 axis: Axis = ...,
4986 ascending: bool | Sequence[bool] = ...,
4987 inplace: Literal[True],
4988 kind: SortKind = ...,
4989 na_position: NaPosition = ...,
4990 ignore_index: bool = ...,
4991 key: ValueKeyFunc = ...,
4992 ) -> None: ...
4994 @overload
4995 def sort_values(
4996 self,
4997 *,
4998 axis: Axis = ...,
4999 ascending: bool | Sequence[bool] = ...,
5000 inplace: bool = ...,
5001 kind: SortKind = ...,
5002 na_position: NaPosition = ...,
5003 ignore_index: bool = ...,
5004 key: ValueKeyFunc = ...,
5005 ) -> Self | None: ...
5007 def sort_values(
5008 self,
5009 *,
5010 axis: Axis = 0,
5011 ascending: bool | Sequence[bool] = True,
5012 inplace: bool = False,
5013 kind: SortKind = "quicksort",
5014 na_position: NaPosition = "last",
5015 ignore_index: bool = False,
5016 key: ValueKeyFunc | None = None,
5017 ) -> Self | None:
5018 """
5019 Sort by the values along either axis.
5021 Parameters
5022 ----------%(optional_by)s
5023 axis : %(axes_single_arg)s, default 0
5024 Axis to be sorted.
5025 ascending : bool or list of bool, default True
5026 Sort ascending vs. descending. Specify list for multiple sort
5027 orders. If this is a list of bools, must match the length of
5028 the by.
5029 inplace : bool, default False
5030 If True, perform operation in-place.
5031 kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, default 'quicksort'
5032 Choice of sorting algorithm. See also :func:`numpy.sort` for more
5033 information. `mergesort` and `stable` are the only stable algorithms. For
5034 DataFrames, this option is only applied when sorting on a single
5035 column or label.
5036 na_position : {'first', 'last'}, default 'last'
5037 Puts NaNs at the beginning if `first`; `last` puts NaNs at the
5038 end.
5039 ignore_index : bool, default False
5040 If True, the resulting axis will be labeled 0, 1, …, n - 1.
5041 key : callable, optional
5042 Apply the key function to the values
5043 before sorting. This is similar to the `key` argument in the
5044 builtin :meth:`sorted` function, with the notable difference that
5045 this `key` function should be *vectorized*. It should expect a
5046 ``Series`` and return a Series with the same shape as the input.
5047 It will be applied to each column in `by` independently. The values in the
5048 returned Series will be used as the keys for sorting.
5050 Returns
5051 -------
5052 DataFrame or None
5053 DataFrame with sorted values or None if ``inplace=True``.
5055 See Also
5056 --------
5057 DataFrame.sort_index : Sort a DataFrame by the index.
5058 Series.sort_values : Similar method for a Series.
5060 Examples
5061 --------
5062 >>> df = pd.DataFrame(
5063 ... {
5064 ... "col1": ["A", "A", "B", np.nan, "D", "C"],
5065 ... "col2": [2, 1, 9, 8, 7, 4],
5066 ... "col3": [0, 1, 9, 4, 2, 3],
5067 ... "col4": ["a", "B", "c", "D", "e", "F"],
5068 ... }
5069 ... )
5070 >>> df
5071 col1 col2 col3 col4
5072 0 A 2 0 a
5073 1 A 1 1 B
5074 2 B 9 9 c
5075 3 NaN 8 4 D
5076 4 D 7 2 e
5077 5 C 4 3 F
5079 Sort by col1
5081 >>> df.sort_values(by=["col1"])
5082 col1 col2 col3 col4
5083 0 A 2 0 a
5084 1 A 1 1 B
5085 2 B 9 9 c
5086 5 C 4 3 F
5087 4 D 7 2 e
5088 3 NaN 8 4 D
5090 Sort by multiple columns
5092 >>> df.sort_values(by=["col1", "col2"])
5093 col1 col2 col3 col4
5094 1 A 1 1 B
5095 0 A 2 0 a
5096 2 B 9 9 c
5097 5 C 4 3 F
5098 4 D 7 2 e
5099 3 NaN 8 4 D
5101 Sort Descending
5103 >>> df.sort_values(by="col1", ascending=False)
5104 col1 col2 col3 col4
5105 4 D 7 2 e
5106 5 C 4 3 F
5107 2 B 9 9 c
5108 0 A 2 0 a
5109 1 A 1 1 B
5110 3 NaN 8 4 D
5112 Putting NAs first
5114 >>> df.sort_values(by="col1", ascending=False, na_position="first")
5115 col1 col2 col3 col4
5116 3 NaN 8 4 D
5117 4 D 7 2 e
5118 5 C 4 3 F
5119 2 B 9 9 c
5120 0 A 2 0 a
5121 1 A 1 1 B
5123 Sorting with a key function
5125 >>> df.sort_values(by="col4", key=lambda col: col.str.lower())
5126 col1 col2 col3 col4
5127 0 A 2 0 a
5128 1 A 1 1 B
5129 2 B 9 9 c
5130 3 NaN 8 4 D
5131 4 D 7 2 e
5132 5 C 4 3 F
5134 Natural sort with the key argument,
5135 using the `natsort <https://github.com/SethMMorton/natsort>` package.
5137 >>> df = pd.DataFrame(
5138 ... {
5139 ... "hours": ["0hr", "128hr", "0hr", "64hr", "64hr", "128hr"],
5140 ... "mins": [
5141 ... "10mins",
5142 ... "40mins",
5143 ... "40mins",
5144 ... "40mins",
5145 ... "10mins",
5146 ... "10mins",
5147 ... ],
5148 ... "value": [10, 20, 30, 40, 50, 60],
5149 ... }
5150 ... )
5151 >>> df
5152 hours mins value
5153 0 0hr 10mins 10
5154 1 128hr 40mins 20
5155 2 0hr 40mins 30
5156 3 64hr 40mins 40
5157 4 64hr 10mins 50
5158 5 128hr 10mins 60
5159 >>> from natsort import natsort_keygen
5160 >>> df.sort_values(
5161 ... by=["hours", "mins"],
5162 ... key=natsort_keygen(),
5163 ... )
5164 hours mins value
5165 0 0hr 10mins 10
5166 2 0hr 40mins 30
5167 4 64hr 10mins 50
5168 3 64hr 40mins 40
5169 5 128hr 10mins 60
5170 1 128hr 40mins 20
5171 """
5172 raise AbstractMethodError(self)
5174 @overload
5175 def sort_index(
5176 self,
5177 *,
5178 axis: Axis = ...,
5179 level: IndexLabel = ...,
5180 ascending: bool | Sequence[bool] = ...,
5181 inplace: Literal[True],
5182 kind: SortKind = ...,
5183 na_position: NaPosition = ...,
5184 sort_remaining: bool = ...,
5185 ignore_index: bool = ...,
5186 key: IndexKeyFunc = ...,
5187 ) -> None: ...
5189 @overload
5190 def sort_index(
5191 self,
5192 *,
5193 axis: Axis = ...,
5194 level: IndexLabel = ...,
5195 ascending: bool | Sequence[bool] = ...,
5196 inplace: Literal[False] = ...,
5197 kind: SortKind = ...,
5198 na_position: NaPosition = ...,
5199 sort_remaining: bool = ...,
5200 ignore_index: bool = ...,
5201 key: IndexKeyFunc = ...,
5202 ) -> Self: ...
5204 @overload
5205 def sort_index(
5206 self,
5207 *,
5208 axis: Axis = ...,
5209 level: IndexLabel = ...,
5210 ascending: bool | Sequence[bool] = ...,
5211 inplace: bool = ...,
5212 kind: SortKind = ...,
5213 na_position: NaPosition = ...,
5214 sort_remaining: bool = ...,
5215 ignore_index: bool = ...,
5216 key: IndexKeyFunc = ...,
5217 ) -> Self | None: ...
5219 def sort_index(
5220 self,
5221 *,
5222 axis: Axis = 0,
5223 level: IndexLabel | None = None,
5224 ascending: bool | Sequence[bool] = True,
5225 inplace: bool = False,
5226 kind: SortKind = "quicksort",
5227 na_position: NaPosition = "last",
5228 sort_remaining: bool = True,
5229 ignore_index: bool = False,
5230 key: IndexKeyFunc | None = None,
5231 ) -> Self | None:
5232 inplace = validate_bool_kwarg(inplace, "inplace")
5233 axis = self._get_axis_number(axis)
5234 ascending = validate_ascending(ascending)
5236 target = self._get_axis(axis)
5238 indexer = get_indexer_indexer(
5239 target, level, ascending, kind, na_position, sort_remaining, key
5240 )
5242 if indexer is None:
5243 if inplace:
5244 result = self
5245 else:
5246 result = self.copy(deep=False)
5248 if ignore_index:
5249 if axis == 1:
5250 result.columns = default_index(len(self.columns))
5251 else:
5252 result.index = default_index(len(self))
5253 if inplace:
5254 return None
5255 else:
5256 return result
5258 baxis = self._get_block_manager_axis(axis)
5259 new_data = self._mgr.take(indexer, axis=baxis, verify=False)
5261 # reconstruct axis if needed
5262 if not ignore_index:
5263 new_axis = new_data.axes[baxis]._sort_levels_monotonic()
5264 else:
5265 new_axis = default_index(len(indexer))
5266 new_data.set_axis(baxis, new_axis)
5268 result = self._constructor_from_mgr(new_data, axes=new_data.axes)
5270 if inplace:
5271 return self._update_inplace(result)
5272 else:
5273 return result.__finalize__(self, method="sort_index")
5275 def reindex(
5276 self,
5277 labels=None,
5278 *,
5279 index=None,
5280 columns=None,
5281 axis: Axis | None = None,
5282 method: ReindexMethod | None = None,
5283 copy: bool | lib.NoDefault = lib.no_default,
5284 level: Level | None = None,
5285 fill_value: Scalar | None = np.nan,
5286 limit: int | None = None,
5287 tolerance=None,
5288 ) -> Self:
5289 """
5290 Conform Series/DataFrame to new index with optional filling logic.
5292 Places NA/NaN in locations having no value in the previous index. A new object
5293 is produced unless the new index is equivalent to the current one and
5294 ``copy=False``.
5296 Parameters
5297 ----------
5298 method : {None, 'backfill'/'bfill', 'pad'/'ffill', 'nearest'}
5299 Method to use for filling holes in reindexed DataFrame.
5300 Please note: this is only applicable to DataFrames/Series with a
5301 monotonically increasing/decreasing index.
5303 * None (default): don't fill gaps
5304 * pad / ffill: Propagate last valid observation forward to next
5305 valid.
5306 * backfill / bfill: Use next valid observation to fill gap.
5307 * nearest: Use nearest valid observations to fill gap.
5309 copy : bool, default False
5310 This keyword is now ignored; changing its value will have no
5311 impact on the method.
5313 .. deprecated:: 3.0.0
5315 This keyword is ignored and will be removed in pandas 4.0. Since
5316 pandas 3.0, this method always returns a new object using a lazy
5317 copy mechanism that defers copies until necessary
5318 (Copy-on-Write). See the `user guide on Copy-on-Write
5319 <https://pandas.pydata.org/docs/dev/user_guide/migration.html>`__
5320 for more details.
5322 level : int or name
5323 Match index values on the specified level of a MultiIndex.
5324 The MultiIndex may be on either the calling object or the
5325 target index; using ``level`` when both are MultiIndexes is
5326 ambiguous and raises a ``TypeError``.
5327 fill_value : scalar, default np.nan
5328 Value to use for missing values. Defaults to NaN, but can be any
5329 "compatible" value.
5330 limit : int, default None
5331 Maximum number of consecutive elements to forward or backward fill.
5332 tolerance : optional
5333 Maximum distance between original and new labels for inexact
5334 matches. The values of the index at the matching locations most
5335 satisfy the equation ``abs(index[indexer] - target) <= tolerance``.
5337 Tolerance may be a scalar value, which applies the same tolerance
5338 to all values, or list-like, which applies variable tolerance per
5339 element. List-like includes list, tuple, array, Series, and must be
5340 the same size as the index and its dtype must exactly match the
5341 index's type.
5343 Returns
5344 -------
5345 Series/DataFrame
5346 Series/DataFrame with changed index.
5348 See Also
5349 --------
5350 DataFrame.set_index : Set row labels.
5351 DataFrame.reset_index : Remove row labels or move them to new columns.
5352 DataFrame.reindex_like : Change to same indices as other DataFrame.
5354 Examples
5355 --------
5356 ``DataFrame.reindex`` supports two calling conventions
5358 * ``(index=index_labels, columns=column_labels, ...)``
5359 * ``(labels, axis={'index', 'columns'}, ...)``
5361 We *highly* recommend using keyword arguments to clarify your
5362 intent.
5364 Create a DataFrame with some fictional data.
5366 >>> index = ["Firefox", "Chrome", "Safari", "IE10", "Konqueror"]
5367 >>> columns = ["http_status", "response_time"]
5368 >>> df = pd.DataFrame(
5369 ... [[200, 0.04], [200, 0.02], [404, 0.07], [404, 0.08], [301, 1.0]],
5370 ... columns=columns,
5371 ... index=index,
5372 ... )
5373 >>> df
5374 http_status response_time
5375 Firefox 200 0.04
5376 Chrome 200 0.02
5377 Safari 404 0.07
5378 IE10 404 0.08
5379 Konqueror 301 1.00
5381 Create a new index and reindex the DataFrame. By default
5382 values in the new index that do not have corresponding
5383 records in the DataFrame are assigned ``NaN``.
5385 >>> new_index = ["Safari", "Iceweasel", "Comodo Dragon", "IE10", "Chrome"]
5386 >>> df.reindex(new_index)
5387 http_status response_time
5388 Safari 404.0 0.07
5389 Iceweasel NaN NaN
5390 Comodo Dragon NaN NaN
5391 IE10 404.0 0.08
5392 Chrome 200.0 0.02
5394 We can fill in the missing values by passing a value to
5395 the keyword ``fill_value``. Because the index is not monotonically
5396 increasing or decreasing, we cannot use arguments to the keyword
5397 ``method`` to fill the ``NaN`` values.
5399 >>> df.reindex(new_index, fill_value=0)
5400 http_status response_time
5401 Safari 404 0.07
5402 Iceweasel 0 0.00
5403 Comodo Dragon 0 0.00
5404 IE10 404 0.08
5405 Chrome 200 0.02
5407 We can also reindex the columns.
5409 >>> df.reindex(columns=["http_status", "user_agent"])
5410 http_status user_agent
5411 Firefox 200 NaN
5412 Chrome 200 NaN
5413 Safari 404 NaN
5414 IE10 404 NaN
5415 Konqueror 301 NaN
5417 Or we can use "axis-style" keyword arguments
5419 >>> df.reindex(["http_status", "user_agent"], axis="columns")
5420 http_status user_agent
5421 Firefox 200 NaN
5422 Chrome 200 NaN
5423 Safari 404 NaN
5424 IE10 404 NaN
5425 Konqueror 301 NaN
5427 To further illustrate the filling functionality in
5428 ``reindex``, we will create a DataFrame with a
5429 monotonically increasing index (for example, a sequence
5430 of dates).
5432 >>> date_index = pd.date_range("1/1/2010", periods=6, freq="D")
5433 >>> df2 = pd.DataFrame(
5434 ... {"prices": [100, 101, np.nan, 100, 89, 88]}, index=date_index
5435 ... )
5436 >>> df2
5437 prices
5438 2010-01-01 100.0
5439 2010-01-02 101.0
5440 2010-01-03 NaN
5441 2010-01-04 100.0
5442 2010-01-05 89.0
5443 2010-01-06 88.0
5445 Suppose we decide to expand the DataFrame to cover a wider
5446 date range.
5448 >>> date_index2 = pd.date_range("12/29/2009", periods=10, freq="D")
5449 >>> df2.reindex(date_index2)
5450 prices
5451 2009-12-29 NaN
5452 2009-12-30 NaN
5453 2009-12-31 NaN
5454 2010-01-01 100.0
5455 2010-01-02 101.0
5456 2010-01-03 NaN
5457 2010-01-04 100.0
5458 2010-01-05 89.0
5459 2010-01-06 88.0
5460 2010-01-07 NaN
5462 The index entries that did not have a value in the original data frame
5463 (for example, '2009-12-29') are by default filled with ``NaN``.
5464 If desired, we can fill in the missing values using one of several
5465 options.
5467 For example, to back-propagate the last valid value to fill the ``NaN``
5468 values, pass ``bfill`` as an argument to the ``method`` keyword.
5470 >>> df2.reindex(date_index2, method="bfill")
5471 prices
5472 2009-12-29 100.0
5473 2009-12-30 100.0
5474 2009-12-31 100.0
5475 2010-01-01 100.0
5476 2010-01-02 101.0
5477 2010-01-03 NaN
5478 2010-01-04 100.0
5479 2010-01-05 89.0
5480 2010-01-06 88.0
5481 2010-01-07 NaN
5483 Please note that the ``NaN`` value present in the original DataFrame
5484 (at index value 2010-01-03) will not be filled by any of the
5485 value propagation schemes. This is because filling while reindexing
5486 does not look at DataFrame values, but only compares the original and
5487 desired indexes. If you do want to fill in the ``NaN`` values present
5488 in the original DataFrame, use the ``fillna()`` method.
5490 See the :ref:`user guide <basics.reindexing>` for more.
5491 """
5492 # TODO: Decide if we care about having different examples for different
5493 # kinds
5495 # Automatically detect matching level when reindexing from Index to MultiIndex.
5496 # This prevents values from being incorrectly set to NaN when the source index
5497 # name matches a index name in the target MultiIndex
5498 if (
5499 level is None
5500 and index is not None
5501 and isinstance(index, MultiIndex)
5502 and not isinstance(self.index, MultiIndex)
5503 and self.index.name in index.names
5504 ):
5505 level = self.index.name
5506 self._check_copy_deprecation(copy)
5508 if index is not None and columns is not None and labels is not None:
5509 raise TypeError("Cannot specify all of 'labels', 'index', 'columns'.")
5510 elif index is not None or columns is not None:
5511 if axis is not None:
5512 raise TypeError(
5513 "Cannot specify both 'axis' and any of 'index' or 'columns'"
5514 )
5515 if labels is not None:
5516 if index is not None:
5517 columns = labels
5518 else:
5519 index = labels
5520 elif axis and self._get_axis_number(axis) == 1:
5521 columns = labels
5522 else:
5523 index = labels
5524 axes: dict[Literal["index", "columns"], Any] = {
5525 "index": index,
5526 "columns": columns,
5527 }
5528 method = clean_reindex_fill_method(method)
5530 # if all axes that are requested to reindex are equal, then only copy
5531 # if indicated must have index names equal here as well as values
5532 if all(
5533 self._get_axis(axis_name).identical(ax)
5534 for axis_name, ax in axes.items()
5535 if ax is not None
5536 ):
5537 return self.copy(deep=False)
5539 # check if we are a multi reindex
5540 if self._needs_reindex_multi(axes, method, level):
5541 return self._reindex_multi(axes, fill_value)
5543 # perform the reindex on the axes
5544 return self._reindex_axes(
5545 axes, level, limit, tolerance, method, fill_value
5546 ).__finalize__(self, method="reindex")
5548 @final
5549 def _reindex_axes(
5550 self,
5551 axes,
5552 level: Level | None,
5553 limit: int | None,
5554 tolerance,
5555 method,
5556 fill_value: Scalar | None,
5557 ) -> Self:
5558 """Perform the reindex for all the axes."""
5559 obj = self
5560 for a in self._AXIS_ORDERS:
5561 labels = axes[a]
5562 if labels is None:
5563 continue
5565 ax = self._get_axis(a)
5566 new_index, indexer = ax.reindex(
5567 labels, level=level, limit=limit, tolerance=tolerance, method=method
5568 )
5570 axis = self._get_axis_number(a)
5571 obj = obj._reindex_with_indexers(
5572 {axis: [new_index, indexer]},
5573 fill_value=fill_value,
5574 allow_dups=False,
5575 )
5577 return obj
5579 def _needs_reindex_multi(self, axes, method, level: Level | None) -> bool:
5580 """Check if we do need a multi reindex."""
5581 return (
5582 (common.count_not_none(*axes.values()) == self._AXIS_LEN)
5583 and method is None
5584 and level is None
5585 # reindex_multi calls self.values, so we only want to go
5586 # down that path when doing so is cheap.
5587 and self._can_fast_transpose
5588 )
5590 def _reindex_multi(self, axes, fill_value):
5591 raise AbstractMethodError(self)
5593 @final
5594 def _reindex_with_indexers(
5595 self,
5596 reindexers,
5597 fill_value=None,
5598 allow_dups: bool = False,
5599 ) -> Self:
5600 """allow_dups indicates an internal call here"""
5601 # reindex doing multiple operations on different axes if indicated
5602 new_data = self._mgr
5603 for axis in sorted(reindexers.keys()):
5604 index, indexer = reindexers[axis]
5605 baxis = self._get_block_manager_axis(axis)
5607 if index is None:
5608 continue
5610 index = ensure_index(index)
5611 if indexer is not None:
5612 indexer = ensure_platform_int(indexer)
5614 # TODO: speed up on homogeneous DataFrame objects (see _reindex_multi)
5615 new_data = new_data.reindex_indexer(
5616 index,
5617 indexer,
5618 axis=baxis,
5619 fill_value=fill_value,
5620 allow_dups=allow_dups,
5621 )
5623 if new_data is self._mgr:
5624 new_data = new_data.copy(deep=False)
5626 return self._constructor_from_mgr(new_data, axes=new_data.axes).__finalize__(
5627 self
5628 )
5630 def filter(
5631 self,
5632 arg=None,
5633 /,
5634 like: str | None = None,
5635 regex: str | None = None,
5636 axis: Axis | None = None,
5637 *,
5638 items=None,
5639 cond=None,
5640 na: Literal["raise"] | bool = False,
5641 ) -> Self:
5642 """
5643 Subset the rows or columns according to a boolean mask or the labels.
5645 Rows (or columns with ``axis=1``) are kept where a boolean mask is
5646 True, or selected by their labels with ``items``, ``like``, or
5647 ``regex``.
5649 Parameters
5650 ----------
5651 arg : callable, expression, or list-like, optional
5652 Positional-only. A callable or an expression created with
5653 :func:`pandas.col` is a boolean mask, see ``cond``. Any other
5654 list-like selects labels, see ``items``. A list-like of booleans
5655 also selects labels, but since it is likely intended as a mask a
5656 warning is issued; pass ``items`` or ``cond`` instead to be
5657 explicit.
5658 like : str
5659 Keep labels from axis for which "like in label == True". This
5660 will be deprecated in a future version; use
5661 ``obj.filter(lambda obj: obj.columns.astype(str).str.contains(like,
5662 regex=False), axis=1)`` instead.
5663 regex : str (regular expression)
5664 Keep labels from axis for which re.search(regex, label) == True.
5665 This will be deprecated in a future version; use
5666 ``obj.filter(lambda obj: obj.columns.astype(str).str.contains(regex),
5667 axis=1)`` instead.
5668 axis : {0 or 'index', 1 or 'columns', None}, default None
5669 The axis to filter on, expressed either as an index (int)
5670 or axis name (str). Defaults to the index for a boolean mask,
5671 and to the info axis ('columns' for ``DataFrame``) when
5672 selecting labels. An expression only supports the index. For
5673 ``Series`` this parameter is unused and defaults to ``None``.
5674 items : list-like, optional
5675 Keep labels from axis which are in ``items``. This will be
5676 deprecated in a future version; use :meth:`DataFrame.select`
5677 when all of ``items`` are present in the columns, or
5678 ``obj.loc[:, pd.Index(items).intersection(obj.columns)]`` (or
5679 the equivalent for the index) otherwise.
5680 cond : array-like of bool, callable, or expression, optional
5681 A boolean mask selecting the entries to keep. A :class:`Series`
5682 is aligned with the labels of the filtered axis; any other
5683 array-like must have the same length as that axis. A callable is
5684 called with the object and must return a boolean mask. An
5685 expression such as ``pd.col("a") > 1`` is evaluated against the
5686 DataFrame and is only supported with ``axis=0``.
5688 .. versionadded:: 3.1.0
5690 na : {"raise", True, False}, default False
5691 How to treat missing values in a boolean mask. ``True`` or
5692 ``False`` treats missing values as that value, matching
5693 ``obj[mask]`` for a mask with nullable boolean dtype; ``"raise"``
5694 raises a ``ValueError``. Ignored when selecting labels.
5696 .. versionadded:: 3.1.0
5698 Returns
5699 -------
5700 Same type as caller
5701 The filtered subset of the DataFrame or Series.
5703 Raises
5704 ------
5705 TypeError
5706 If none or more than one of the positional argument, ``items``,
5707 ``cond``, ``like``, and ``regex`` is passed, or if ``cond`` is
5708 not a one-dimensional boolean mask.
5709 ValueError
5710 If a mask contains missing values and ``na="raise"``, if a
5711 boolean array is not one-dimensional, or if an expression is
5712 passed with ``axis=1``.
5713 IndexError
5714 If a mask that is not a Series has a different length than the
5715 filtered axis.
5716 IndexingError
5717 If a Series mask cannot be aligned with the filtered axis.
5719 Warns
5720 -----
5721 UserWarning
5722 If a list-like of booleans is passed positionally.
5724 See Also
5725 --------
5726 DataFrame.loc : Access a group of rows and columns
5727 by label(s) or a boolean array.
5728 DataFrame.where : Replace values where the condition is False.
5730 Notes
5731 -----
5732 The positional argument is a boolean mask only when it is a callable
5733 or an expression; any other value, including a list-like of booleans,
5734 selects labels. Use ``cond`` to filter with a boolean array or
5735 :class:`Series`.
5737 Selecting labels with ``items``, ``like``, or ``regex`` will be
5738 deprecated in a future version.
5740 Examples
5741 --------
5742 >>> df = pd.DataFrame(
5743 ... {"one": [1, 4], "two": [2, 5], "three": [3, 6]},
5744 ... index=["mouse", "rabbit"],
5745 ... )
5746 >>> df
5747 one two three
5748 mouse 1 2 3
5749 rabbit 4 5 6
5751 Filter rows with a boolean Series.
5753 >>> df.filter(cond=df["two"] > 2)
5754 one two three
5755 rabbit 4 5 6
5757 The same using an expression or a callable, which are convenient in
5758 method chains and may be passed positionally.
5760 >>> df.filter(pd.col("two") > 2)
5761 one two three
5762 rabbit 4 5 6
5763 >>> df.filter(lambda df: df["two"] > 2)
5764 one two three
5765 rabbit 4 5 6
5767 Filter columns with a boolean array.
5769 >>> df.filter(cond=df.columns.str.endswith("e"), axis=1)
5770 one three
5771 mouse 1 3
5772 rabbit 4 6
5774 Missing values in the mask are treated as False by default; pass
5775 ``na="raise"`` to raise instead, or ``na=True`` to keep them.
5777 >>> mask = pd.array([True, None], dtype="boolean")
5778 >>> df.filter(cond=mask)
5779 one two three
5780 mouse 1 2 3
5781 >>> df.filter(cond=mask, na=True)
5782 one two three
5783 mouse 1 2 3
5784 rabbit 4 5 6
5786 Select columns by their labels.
5788 >>> df.filter(items=["one", "three"])
5789 one three
5790 mouse 1 3
5791 rabbit 4 6
5792 >>> df.filter(regex="e$", axis=1)
5793 one three
5794 mouse 1 3
5795 rabbit 4 6
5796 >>> df.filter(like="bbi", axis=0)
5797 one two three
5798 rabbit 4 5 6
5799 """
5800 nkw = common.count_not_none(arg, items, cond, like, regex)
5801 if nkw > 1:
5802 raise TypeError(
5803 "The positional argument and the keyword arguments `items`, "
5804 "`cond`, `like`, and `regex` are mutually exclusive"
5805 )
5806 if nkw == 0:
5807 raise TypeError(
5808 "Must pass a positional argument or one of `items`, `cond`, "
5809 "`like`, or `regex`"
5810 )
5812 if na is not True and na is not False and na != "raise":
5813 raise ValueError(f"na must be 'raise', True, or False, got {na!r}")
5815 if arg is not None:
5816 # Only a callable or expression is unambiguously a mask when passed
5817 # positionally. Anything else selected labels before masks were
5818 # supported and keeps doing so, since a boolean list-like is a
5819 # valid (if unusual) list of labels.
5820 if callable(arg):
5821 cond = arg
5822 else:
5823 if is_mask(arg):
5824 warnings.warn(
5825 "A list-like of booleans passed positionally to "
5826 f"{type(self).__name__}.filter selects labels. Pass "
5827 "cond=... to filter with a boolean mask, or items=... "
5828 "to select labels without this warning.",
5829 UserWarning,
5830 stacklevel=find_stack_level(),
5831 )
5832 items = arg
5834 if cond is not None:
5835 mask_axis = 0 if axis is None else self._get_axis_number(axis)
5836 if isinstance(cond, Expression) and self.ndim != 2:
5837 raise TypeError(
5838 "Expressions such as pd.col(...) are only supported by "
5839 "DataFrame.filter"
5840 )
5841 if isinstance(cond, Expression) and mask_axis != 0:
5842 raise ValueError(
5843 "Expressions such as pd.col(...) are only supported by "
5844 f"{type(self).__name__}.filter with axis=0, since they "
5845 "evaluate to a mask aligned with the index"
5846 )
5847 if callable(cond):
5848 # Expression defines __call__, so it enters here too
5849 mask = common.apply_if_callable(cond, self)
5850 if not is_mask(mask):
5851 kind = "expression" if isinstance(cond, Expression) else "callable"
5852 raise TypeError(
5853 f"The {kind} passed to {type(self).__name__}.filter "
5854 "must evaluate to a one-dimensional boolean mask"
5855 )
5856 elif is_mask(cond):
5857 mask = cond
5858 else:
5859 raise TypeError(
5860 f"cond passed to {type(self).__name__}.filter must be a "
5861 "one-dimensional boolean mask"
5862 )
5863 return filter_mask(self, mask, mask_axis, na)
5865 if axis is None:
5866 axis = self._info_axis_name
5867 labels = self._get_axis(axis)
5869 if items is not None:
5870 name = self._get_axis_name(axis)
5871 items = Index(items).intersection(labels)
5872 if len(items) == 0:
5873 # Keep the dtype of labels when we are empty
5874 items = items.astype(labels.dtype)
5875 return self.reindex(**{name: items})
5876 elif like:
5878 def f(x) -> bool:
5879 assert like is not None # needed for mypy
5880 return like in ensure_str(x)
5882 values = labels.map(f)
5883 return self.loc(axis=axis)[values]
5884 elif regex:
5886 def f(x) -> bool:
5887 return matcher.search(ensure_str(x)) is not None
5889 matcher = re.compile(regex)
5890 values = labels.map(f)
5891 return self.loc(axis=axis)[values]
5892 else:
5893 raise TypeError(
5894 "Must pass a positional argument or one of `items`, `cond`, "
5895 "`like`, or `regex`"
5896 )
5898 @final
5899 def head(self, n: int = 5) -> Self:
5900 """
5901 Return the first `n` rows.
5903 This function exhibits the same behavior as ``df[:n]``, returning the
5904 first ``n`` rows based on position. It is useful for quickly checking
5905 if your object has the right type of data in it.
5907 When ``n`` is positive, it returns the first ``n`` rows. For ``n`` equal to 0,
5908 it returns an empty object. When ``n`` is negative, it returns
5909 all rows except the last ``|n|`` rows, mirroring the behavior of ``df[:n]``.
5911 If ``n`` is larger than the number of rows, this function returns all rows.
5913 Parameters
5914 ----------
5915 n : int, default 5
5916 Number of rows to select.
5918 Returns
5919 -------
5920 same type as caller
5921 The first `n` rows of the caller object.
5923 See Also
5924 --------
5925 DataFrame.tail: Returns the last `n` rows.
5927 Examples
5928 --------
5929 >>> df = pd.DataFrame(
5930 ... {
5931 ... "animal": [
5932 ... "alligator",
5933 ... "bee",
5934 ... "falcon",
5935 ... "lion",
5936 ... "monkey",
5937 ... "parrot",
5938 ... "shark",
5939 ... "whale",
5940 ... "zebra",
5941 ... ]
5942 ... }
5943 ... )
5944 >>> df
5945 animal
5946 0 alligator
5947 1 bee
5948 2 falcon
5949 3 lion
5950 4 monkey
5951 5 parrot
5952 6 shark
5953 7 whale
5954 8 zebra
5956 Viewing the first 5 lines
5958 >>> df.head()
5959 animal
5960 0 alligator
5961 1 bee
5962 2 falcon
5963 3 lion
5964 4 monkey
5966 Viewing the first `n` lines (three in this case)
5968 >>> df.head(3)
5969 animal
5970 0 alligator
5971 1 bee
5972 2 falcon
5974 For negative values of `n`
5976 >>> df.head(-3)
5977 animal
5978 0 alligator
5979 1 bee
5980 2 falcon
5981 3 lion
5982 4 monkey
5983 5 parrot
5984 """
5985 return self.iloc[:n].copy()
5987 @final
5988 def tail(self, n: int = 5) -> Self:
5989 """
5990 Return the last `n` rows.
5992 This function returns last `n` rows from the object based on
5993 position. It is useful for quickly verifying data, for example,
5994 after sorting or appending rows.
5996 For negative values of `n`, this function returns all rows except
5997 the first `|n|` rows, equivalent to ``df[|n|:]``.
5999 If ``n`` is larger than the number of rows, this function returns all rows.
6001 Parameters
6002 ----------
6003 n : int, default 5
6004 Number of rows to select.
6006 Returns
6007 -------
6008 type of caller
6009 The last `n` rows of the caller object.
6011 See Also
6012 --------
6013 DataFrame.head : The first `n` rows of the caller object.
6015 Examples
6016 --------
6017 >>> df = pd.DataFrame(
6018 ... {
6019 ... "animal": [
6020 ... "alligator",
6021 ... "bee",
6022 ... "falcon",
6023 ... "lion",
6024 ... "monkey",
6025 ... "parrot",
6026 ... "shark",
6027 ... "whale",
6028 ... "zebra",
6029 ... ]
6030 ... }
6031 ... )
6032 >>> df
6033 animal
6034 0 alligator
6035 1 bee
6036 2 falcon
6037 3 lion
6038 4 monkey
6039 5 parrot
6040 6 shark
6041 7 whale
6042 8 zebra
6044 Viewing the last 5 lines
6046 >>> df.tail()
6047 animal
6048 4 monkey
6049 5 parrot
6050 6 shark
6051 7 whale
6052 8 zebra
6054 Viewing the last `n` lines (three in this case)
6056 >>> df.tail(3)
6057 animal
6058 6 shark
6059 7 whale
6060 8 zebra
6062 For negative values of `n`
6064 >>> df.tail(-3)
6065 animal
6066 3 lion
6067 4 monkey
6068 5 parrot
6069 6 shark
6070 7 whale
6071 8 zebra
6072 """
6073 if n == 0:
6074 return self.iloc[0:0].copy()
6075 return self.iloc[-n:].copy()
6077 @final
6078 def sample(
6079 self,
6080 n: int | None = None,
6081 frac: float | None = None,
6082 replace: bool = False,
6083 weights=None,
6084 random_state: RandomState | None = None,
6085 axis: Axis | None = None,
6086 ignore_index: bool = False,
6087 ) -> Self:
6088 """
6089 Return a random sample of items from an axis of object.
6091 You can use `random_state` for reproducibility.
6093 Parameters
6094 ----------
6095 n : int, optional
6096 Number of items from axis to return. Cannot be used with `frac`.
6097 Default = 1 if `frac` = None.
6098 frac : float, optional
6099 Fraction of axis items to return. Cannot be used with `n`.
6100 replace : bool, default False
6101 Allow or disallow sampling of the same row more than once.
6102 weights : str or ndarray-like, optional
6103 Default ``None`` results in equal probability weighting.
6104 If passed a Series, will align with target object on index. Index
6105 values in weights not found in sampled object will be ignored and
6106 index values in sampled object not in weights will be assigned
6107 weights of zero.
6108 If called on a DataFrame, will accept the name of a column
6109 when axis = 0.
6110 Unless weights are a Series, weights must be same length as axis
6111 being sampled.
6112 If weights do not sum to 1, they will be normalized to sum to 1.
6113 Missing values in the weights column will be treated as zero.
6114 Infinite values not allowed.
6115 When replace = False will not allow ``(n * max(weights) / sum(weights)) > 1``
6116 in order to avoid biased results. See the Notes below for more details.
6117 random_state : int, array-like, BitGenerator, np.random.RandomState, np.random.Generator, optional
6118 If int, array-like, or BitGenerator, seed for random number generator.
6119 If np.random.RandomState or np.random.Generator, use as given.
6120 Default ``None`` results in sampling with the current state of np.random.
6121 axis : {0 or 'index', 1 or 'columns', None}, default None
6122 Axis to sample. Accepts axis number or name. Default is stat axis
6123 for given data type. For `Series` this parameter is unused and defaults to `None`.
6124 ignore_index : bool, default False
6125 If True, the resulting index will be labeled 0, 1, …, n - 1.
6127 Returns
6128 -------
6129 Series or DataFrame
6130 A new object of same type as caller containing `n` items randomly
6131 sampled from the caller object.
6133 See Also
6134 --------
6135 DataFrameGroupBy.sample: Generates random samples from each group of a
6136 DataFrame object.
6137 SeriesGroupBy.sample: Generates random samples from each group of a
6138 Series object.
6139 numpy.random.choice: Generates a random sample from a given 1-D numpy
6140 array.
6142 Notes
6143 -----
6144 If `frac` > 1, `replacement` should be set to `True`.
6146 When replace = False will not allow ``(n * max(weights) / sum(weights)) > 1``,
6147 since that would cause results to be biased. E.g. sampling 2 items without replacement
6148 with weights [100, 1, 1] would yield two last items in 1/2 of cases, instead of 1/102.
6149 This is similar to specifying `n=4` without replacement on a Series with 3 elements.
6151 Examples
6152 --------
6153 >>> df = pd.DataFrame(
6154 ... {
6155 ... "num_legs": [2, 4, 8, 0],
6156 ... "num_wings": [2, 0, 0, 0],
6157 ... "num_specimen_seen": [10, 2, 1, 8],
6158 ... },
6159 ... index=["falcon", "dog", "spider", "fish"],
6160 ... )
6161 >>> df
6162 num_legs num_wings num_specimen_seen
6163 falcon 2 2 10
6164 dog 4 0 2
6165 spider 8 0 1
6166 fish 0 0 8
6168 Extract 3 random elements from the ``Series`` ``df['num_legs']``:
6169 Note that we use `random_state` to ensure the reproducibility of
6170 the examples.
6172 >>> df["num_legs"].sample(n=3, random_state=1)
6173 fish 0
6174 spider 8
6175 falcon 2
6176 Name: num_legs, dtype: int64
6178 A random 50% sample of the ``DataFrame`` with replacement:
6180 >>> df.sample(frac=0.5, replace=True, random_state=1)
6181 num_legs num_wings num_specimen_seen
6182 dog 4 0 2
6183 fish 0 0 8
6185 An upsample sample of the ``DataFrame`` with replacement:
6186 Note that `replace` parameter has to be `True` for `frac` parameter > 1.
6188 >>> df.sample(frac=2, replace=True, random_state=1)
6189 num_legs num_wings num_specimen_seen
6190 dog 4 0 2
6191 fish 0 0 8
6192 falcon 2 2 10
6193 falcon 2 2 10
6194 fish 0 0 8
6195 dog 4 0 2
6196 fish 0 0 8
6197 dog 4 0 2
6199 Using a DataFrame column as weights. Rows with larger value in the
6200 `num_specimen_seen` column are more likely to be sampled.
6202 >>> df.sample(n=2, weights="num_specimen_seen", random_state=1)
6203 num_legs num_wings num_specimen_seen
6204 falcon 2 2 10
6205 fish 0 0 8
6206 """ # noqa: E501
6207 if axis is None:
6208 axis = 0
6210 axis = self._get_axis_number(axis)
6211 obj_len = self.shape[axis]
6213 # Process random_state argument
6214 rs = common.random_state(random_state)
6216 size = sample.process_sampling_size(n, frac, replace)
6217 if size is None:
6218 assert frac is not None
6219 size = round(frac * obj_len)
6221 if weights is not None:
6222 weights = sample.preprocess_weights(self, weights, axis)
6224 sampled_indices = sample.sample(obj_len, size, replace, weights, rs)
6225 result = self.take(sampled_indices, axis=axis)
6227 if ignore_index:
6228 result.index = default_index(len(result))
6230 return result
6232 @overload
6233 def pipe(
6234 self,
6235 func: Callable[Concatenate[Self, P], T],
6236 *args: P.args,
6237 **kwargs: P.kwargs,
6238 ) -> T: ...
6240 @overload
6241 def pipe(
6242 self,
6243 func: tuple[Callable[..., T], str],
6244 *args: Any,
6245 **kwargs: Any,
6246 ) -> T: ...
6248 @final
6249 def pipe(
6250 self,
6251 func: Callable[Concatenate[Self, P], T] | tuple[Callable[..., T], str],
6252 *args: Any,
6253 **kwargs: Any,
6254 ) -> T:
6255 r"""
6256 Apply chainable functions that expect Series or DataFrames.
6258 Passes the object as the first argument to each function, so
6259 that ``df.pipe(f).pipe(g)`` is equivalent to ``g(f(df))``.
6260 Improves readability when chaining several transformations.
6262 Parameters
6263 ----------
6264 func : function
6265 Function to apply to the Series/DataFrame.
6266 ``args``, and ``kwargs`` are passed into ``func``.
6267 Alternatively a ``(callable, data_keyword)`` tuple where
6268 ``data_keyword`` is a string indicating the keyword of
6269 ``callable`` that expects the Series/DataFrame.
6270 *args : iterable, optional
6271 Positional arguments passed into ``func``.
6272 **kwargs : mapping, optional
6273 A dictionary of keyword arguments passed into ``func``.
6275 Returns
6276 -------
6277 The return type of ``func``.
6278 The result of applying ``func`` to the Series or DataFrame.
6280 See Also
6281 --------
6282 DataFrame.apply : Apply a function along input axis of DataFrame.
6283 DataFrame.map : Apply a function elementwise on a whole DataFrame.
6284 Series.map : Apply a mapping correspondence on a
6285 :class:`~pandas.Series`.
6287 Notes
6288 -----
6289 Use ``.pipe`` when chaining together functions that expect
6290 Series, DataFrames or GroupBy objects.
6292 Examples
6293 --------
6294 Constructing an income DataFrame from a dictionary.
6296 >>> data = [[8000, 1000], [9500, np.nan], [5000, 2000]]
6297 >>> df = pd.DataFrame(data, columns=["Salary", "Others"])
6298 >>> df
6299 Salary Others
6300 0 8000 1000.0
6301 1 9500 NaN
6302 2 5000 2000.0
6304 Functions that perform tax reductions on an income DataFrame.
6306 >>> def subtract_federal_tax(df):
6307 ... return df * 0.9
6308 >>> def subtract_state_tax(df, rate):
6309 ... return df * (1 - rate)
6310 >>> def subtract_national_insurance(df, rate, rate_increase):
6311 ... new_rate = rate + rate_increase
6312 ... return df * (1 - new_rate)
6314 Instead of writing
6316 >>> subtract_national_insurance(
6317 ... subtract_state_tax(subtract_federal_tax(df), rate=0.12),
6318 ... rate=0.05,
6319 ... rate_increase=0.02,
6320 ... ) # doctest: +SKIP
6322 You can write
6324 >>> (
6325 ... df.pipe(subtract_federal_tax)
6326 ... .pipe(subtract_state_tax, rate=0.12)
6327 ... .pipe(subtract_national_insurance, rate=0.05, rate_increase=0.02)
6328 ... )
6329 Salary Others
6330 0 5892.48 736.56
6331 1 6997.32 NaN
6332 2 3682.80 1473.12
6334 If you have a function that takes the data as (say) the second
6335 argument, pass a tuple indicating which keyword expects the
6336 data. For example, suppose ``national_insurance`` takes its data as ``df``
6337 in the second argument:
6339 >>> def subtract_national_insurance(rate, df, rate_increase):
6340 ... new_rate = rate + rate_increase
6341 ... return df * (1 - new_rate)
6342 >>> (
6343 ... df.pipe(subtract_federal_tax)
6344 ... .pipe(subtract_state_tax, rate=0.12)
6345 ... .pipe(
6346 ... (subtract_national_insurance, "df"), rate=0.05, rate_increase=0.02
6347 ... )
6348 ... )
6349 Salary Others
6350 0 5892.48 736.56
6351 1 6997.32 NaN
6352 2 3682.80 1473.12
6353 """
6354 return common.pipe(self.copy(deep=False), func, *args, **kwargs)
6356 # ----------------------------------------------------------------------
6357 # Attribute access
6359 @final
6360 def __finalize__(self, other, method: str | None = None, **kwargs) -> Self:
6361 """
6362 Propagate metadata from other to self.
6364 This is the default implementation. Subclasses may override this method to
6365 implement their own metadata handling.
6367 Parameters
6368 ----------
6369 other : the object from which to get the attributes that we are going
6370 to propagate. If ``other`` has an ``input_objs`` attribute, then
6371 this attribute must contain an iterable of objects, each with an
6372 ``attrs`` attribute.
6373 method : str, optional
6374 A passed method name providing context on where ``__finalize__``
6375 was called.
6377 .. warning::
6379 The value passed as `method` are not currently considered
6380 stable across pandas releases.
6382 Notes
6383 -----
6384 In case ``other`` has an ``input_objs`` attribute, this method only
6385 propagates its metadata if each object in ``input_objs`` has the exact
6386 same metadata as the others.
6387 """
6388 if isinstance(other, NDFrame):
6389 if other.attrs:
6390 # We want attrs propagation to have minimal performance
6391 # impact if attrs are not used; i.e. attrs is an empty dict.
6392 # One could make the deepcopy unconditionally, but a deepcopy
6393 # of an empty dict is 50x more expensive than the empty check.
6394 self.attrs = deepcopy(other.attrs)
6395 # Since new objects always start with allows_duplicate_labels=True,
6396 # we only need to act when other has it set to False.
6397 if not other._flags._allows_duplicate_labels:
6398 self.flags.allows_duplicate_labels = False
6399 # For subclasses using _metadata.
6400 for name in set(self._metadata) & set(other._metadata):
6401 assert isinstance(name, str)
6402 object.__setattr__(self, name, getattr(other, name, None))
6404 elif hasattr(other, "input_objs"):
6405 objs = other.input_objs
6406 # propagate attrs only if all inputs have the same attrs
6407 if all(bool(obj.attrs) for obj in objs):
6408 # all inputs have non-empty attrs
6409 attrs = objs[0].attrs
6410 have_same_attrs = all(obj.attrs == attrs for obj in objs[1:])
6411 if have_same_attrs:
6412 self.attrs = deepcopy(attrs)
6414 if not all(x._flags._allows_duplicate_labels for x in objs):
6415 self.flags.allows_duplicate_labels = False
6417 return self
6419 @final
6420 def __getattr__(self, name: str):
6421 """
6422 After regular attribute access, try looking up the name
6423 This allows simpler access to columns for interactive use.
6424 """
6425 # Note: obj.x will always call obj.__getattribute__('x') prior to
6426 # calling obj.__getattr__('x').
6427 if (
6428 name not in self._internal_names_set
6429 and name not in self._metadata
6430 and name not in self._accessors
6431 and self._info_axis._can_hold_identifiers_and_holds_name(name)
6432 ):
6433 return self[name]
6434 return object.__getattribute__(self, name)
6436 @final
6437 def __setattr__(self, name: str, value) -> None:
6438 """
6439 After regular attribute access, try setting the name
6440 This allows simpler access to columns for interactive use.
6441 """
6442 # first try regular attribute access via __getattribute__, so that
6443 # e.g. ``obj.x`` and ``obj.x = 4`` will always reference/modify
6444 # the same attribute.
6446 try:
6447 object.__getattribute__(self, name)
6448 return object.__setattr__(self, name, value)
6449 except AttributeError:
6450 pass
6452 # if this fails, go on to more involved attribute setting
6453 # (note that this matches __getattr__, above).
6454 if name in self._internal_names_set:
6455 object.__setattr__(self, name, value)
6456 elif name in self._metadata:
6457 object.__setattr__(self, name, value)
6458 else:
6459 try:
6460 existing = getattr(self, name)
6461 if isinstance(existing, Index):
6462 object.__setattr__(self, name, value)
6463 elif name in self._info_axis:
6464 self[name] = value
6465 else:
6466 object.__setattr__(self, name, value)
6467 except (AttributeError, TypeError):
6468 if isinstance(self, ABCDataFrame) and (is_list_like(value)):
6469 warnings.warn(
6470 "Pandas doesn't allow columns to be "
6471 "created via a new attribute name - see "
6472 "https://pandas.pydata.org/docs/dev/user_guide/"
6473 "indexing.html#attribute-access",
6474 stacklevel=find_stack_level(),
6475 )
6476 object.__setattr__(self, name, value)
6478 @final
6479 def _dir_additions(self) -> set[str]:
6480 """
6481 add the string-like attributes from the info_axis.
6482 If info_axis is a MultiIndex, its first level values are used.
6483 """
6484 additions = super()._dir_additions()
6485 if self._info_axis._can_hold_strings:
6486 additions.update(self._info_axis._dir_additions_for_owner)
6487 return additions
6489 # ----------------------------------------------------------------------
6490 # Consolidation of internals
6492 @final
6493 def _consolidate_inplace(self) -> None:
6494 """Consolidate data in place and return None"""
6496 self._mgr = self._mgr.consolidate()
6498 @final
6499 def _consolidate(self):
6500 """
6501 Compute NDFrame with "consolidated" internals (data of each dtype
6502 grouped together in a single ndarray).
6504 Returns
6505 -------
6506 consolidated : same type as caller
6507 """
6508 cons_data = self._mgr.consolidate()
6509 return self._constructor_from_mgr(cons_data, axes=cons_data.axes).__finalize__(
6510 self
6511 )
6513 @final
6514 @property
6515 def _is_mixed_type(self) -> bool:
6516 if self._mgr.is_single_block:
6517 # Includes all Series cases
6518 return False
6520 if self._mgr.any_extension_types:
6521 # Even if they have the same dtype, we can't consolidate them,
6522 # so we pretend this is "mixed'"
6523 return True
6525 return self.dtypes.nunique() > 1
6527 @final
6528 def _get_numeric_data(self) -> Self:
6529 new_mgr = self._mgr.get_numeric_data()
6530 return self._constructor_from_mgr(new_mgr, axes=new_mgr.axes).__finalize__(self)
6532 @final
6533 def _get_bool_data(self):
6534 new_mgr = self._mgr.get_bool_data()
6535 return self._constructor_from_mgr(new_mgr, axes=new_mgr.axes).__finalize__(self)
6537 # ----------------------------------------------------------------------
6538 # Internal Interface Methods
6540 @property
6541 def values(self):
6542 raise AbstractMethodError(self)
6544 @property
6545 def _values(self) -> ArrayLike:
6546 """internal implementation"""
6547 raise AbstractMethodError(self)
6549 @property
6550 def dtypes(self):
6551 """
6552 Return the dtypes in the DataFrame.
6554 This returns a Series with the data type of each column.
6555 The result's index is the original DataFrame's columns. Columns
6556 with mixed types are stored with the ``object`` dtype. See
6557 :ref:`the User Guide <basics.dtypes>` for more.
6559 Returns
6560 -------
6561 pandas.Series
6562 The data type of each column.
6564 See Also
6565 --------
6566 Series.dtypes : Return the dtype object of the underlying data.
6568 Examples
6569 --------
6570 >>> df = pd.DataFrame(
6571 ... {
6572 ... "float": [1.0],
6573 ... "int": [1],
6574 ... "datetime": [pd.Timestamp("20180310")],
6575 ... "string": ["foo"],
6576 ... }
6577 ... )
6578 >>> df.dtypes
6579 float float64
6580 int int64
6581 datetime datetime64[us]
6582 string str
6583 dtype: object
6584 """
6585 data = self._mgr.get_dtypes()
6586 # copy=False is safe because get_dtypes() returns a new array
6587 return self._constructor_sliced(
6588 data, index=self._info_axis, dtype=np.object_, copy=False
6589 )
6591 @final
6592 def astype(
6593 self,
6594 dtype,
6595 copy: bool | lib.NoDefault = lib.no_default,
6596 errors: IgnoreRaise = "raise",
6597 ) -> Self:
6598 """
6599 Cast a pandas object to a specified dtype ``dtype``.
6601 This method allows the conversion of the data types of pandas objects,
6602 including DataFrames and Series, to the specified dtype. It supports casting
6603 entire objects to a single data type or applying different data types to
6604 individual columns using a mapping.
6606 Parameters
6607 ----------
6608 dtype : str, data type, Series or Mapping of column name -> data type
6609 Use a str, numpy.dtype, pandas.ExtensionDtype or Python type to
6610 cast entire pandas object to the same type. Alternatively, use a
6611 mapping, e.g. {col: dtype, ...}, where col is a column label and dtype is
6612 a numpy.dtype or Python type to cast one or more of the DataFrame's
6613 columns to column-specific types. The mapping may be a ``dict`` or a
6614 :class:`Series` indexed by column label; columns whose labels are
6615 absent from the mapping are left unchanged. A Python type (e.g.
6616 ``int``, ``float``, ``str``, ``bool``) is mapped to the corresponding
6617 dtype; a type with no such mapping, such as ``datetime.datetime``,
6618 raises ``TypeError``.
6619 copy : bool, default False
6620 This keyword is now ignored; changing its value will have no
6621 impact on the method.
6623 .. deprecated:: 3.0.0
6625 This keyword is ignored and will be removed in pandas 4.0. Since
6626 pandas 3.0, this method always returns a new object using a lazy
6627 copy mechanism that defers copies until necessary
6628 (Copy-on-Write). See the `user guide on Copy-on-Write
6629 <https://pandas.pydata.org/docs/dev/user_guide/migration.html>`__
6630 for more details.
6632 errors : {'raise', 'ignore'}, default 'raise'
6633 Control raising of exceptions on invalid data for provided dtype.
6635 - ``raise`` : allow exceptions to be raised
6636 - ``ignore`` : suppress exceptions. On error return original object.
6638 This does not apply to keys in a ``dtype`` mapping that are not
6639 column labels (or, for a Series, not its name); those always raise
6640 ``KeyError``.
6642 Returns
6643 -------
6644 same type as caller
6645 The pandas object casted to the specified ``dtype``.
6647 See Also
6648 --------
6649 to_datetime : Convert argument to datetime.
6650 to_timedelta : Convert argument to timedelta.
6651 to_numeric : Convert argument to a numeric type.
6652 numpy.ndarray.astype : Cast a numpy array to a specified type.
6654 Notes
6655 -----
6656 .. versionchanged:: 2.0.0
6658 Using ``astype`` to convert from timezone-naive dtype to
6659 timezone-aware dtype will raise an exception.
6660 Use :meth:`Series.dt.tz_localize` instead.
6662 Examples
6663 --------
6664 Create a DataFrame:
6666 >>> d = {"col1": [1, 2], "col2": [3, 4]}
6667 >>> df = pd.DataFrame(data=d)
6668 >>> df.dtypes
6669 col1 int64
6670 col2 int64
6671 dtype: object
6673 Cast all columns to int32:
6675 >>> df.astype("int32").dtypes
6676 col1 int32
6677 col2 int32
6678 dtype: object
6680 Cast col1 to int32 using a dictionary:
6682 >>> df.astype({"col1": "int32"}).dtypes
6683 col1 int32
6684 col2 int64
6685 dtype: object
6687 Create a series:
6689 >>> ser = pd.Series([1, 2], dtype="int32")
6690 >>> ser
6691 0 1
6692 1 2
6693 dtype: int32
6694 >>> ser.astype("int64")
6695 0 1
6696 1 2
6697 dtype: int64
6699 Convert to categorical type:
6701 >>> ser.astype("category")
6702 0 1
6703 1 2
6704 dtype: category
6705 Categories (2, int32): [1, 2]
6707 Convert to ordered categorical type with custom ordering:
6709 >>> from pandas.api.types import CategoricalDtype
6710 >>> cat_dtype = CategoricalDtype(categories=[2, 1], ordered=True)
6711 >>> ser.astype(cat_dtype)
6712 0 1
6713 1 2
6714 dtype: category
6715 Categories (2, int64): [2 < 1]
6717 Create a series of dates:
6719 >>> ser_date = pd.Series(pd.date_range("20200101", periods=3))
6720 >>> ser_date
6721 0 2020-01-01
6722 1 2020-01-02
6723 2 2020-01-03
6724 dtype: datetime64[us]
6725 """
6726 self._check_copy_deprecation(copy)
6727 if is_dict_like(dtype):
6728 if self.ndim == 1: # i.e. Series
6729 if len(dtype) > 1 or self.name not in dtype:
6730 raise KeyError(
6731 "Only the Series name can be used for "
6732 "the key in Series dtype mappings."
6733 )
6734 new_type = dtype[self.name]
6735 return self.astype(new_type, errors=errors)
6737 # GH#44417 cast to Series so we can use .iat below, which will be
6738 # robust in case we
6739 from pandas import Series
6741 dtype_ser = Series(dtype, dtype=object)
6743 for col_name in dtype_ser.index:
6744 if col_name not in self:
6745 raise KeyError(
6746 "Only a column name can be used for the "
6747 "key in a dtype mappings argument. "
6748 f"'{col_name}' not found in columns."
6749 )
6751 dtype_ser = dtype_ser.reindex(self.columns, fill_value=None)
6753 results = []
6754 for i, (col_name, col) in enumerate(self.items()):
6755 cdt = dtype_ser.iat[i]
6756 if isna(cdt):
6757 res_col = col.copy(deep=False)
6758 else:
6759 try:
6760 res_col = col.astype(dtype=cdt, errors=errors)
6761 except ValueError as ex:
6762 ex.args = (
6763 f"{ex}: Error while type casting for column '{col_name}'",
6764 )
6765 raise
6766 results.append(res_col)
6768 elif is_extension_array_dtype(dtype) and self.ndim > 1:
6769 # TODO(EA2D): special case not needed with 2D EAs
6770 dtype = pandas_dtype(dtype)
6771 if isinstance(dtype, ExtensionDtype) and all(
6772 x == dtype for x in self._blk_dtypes
6773 ):
6774 return self.copy(deep=False)
6775 # GH 18099/22869: columnwise conversion to extension dtype
6776 # GH 24704: self.items handles duplicate column names
6777 results = [ser.astype(dtype, errors=errors) for _, ser in self.items()]
6779 else:
6780 # else, only a single dtype is given
6781 new_data = self._mgr.astype(dtype=dtype, errors=errors)
6782 res = self._constructor_from_mgr(new_data, axes=new_data.axes)
6783 return res.__finalize__(self, method="astype")
6785 # GH 33113: handle empty frame or series
6786 if not results:
6787 return self.copy(deep=False)
6789 # GH 19920: retain column metadata after concat
6790 result = concat(results, axis=1)
6791 # GH#40810 retain subclass
6792 # error: Incompatible types in assignment
6793 # (expression has type "Self", variable has type "DataFrame")
6794 result = self._constructor(result) # type: ignore[assignment]
6795 result.columns = self.columns
6796 result = result.__finalize__(self, method="astype")
6797 # https://github.com/python/mypy/issues/8354
6798 return cast("Self", result)
6800 @final
6801 def copy(self, deep: bool = True) -> Self:
6802 """
6803 Make a copy of this object's indices and data.
6805 When ``deep=True`` (default), a new object will be created with a
6806 copy of the calling object's data and indices. Modifications to
6807 the data or indices of the copy will not be reflected in the
6808 original object (see notes below).
6810 When ``deep=False``, a new object will be created without copying
6811 the calling object's data or index (only references to the data
6812 and index are copied). With Copy-on-Write, changes to the original
6813 will *not* be reflected in the shallow copy (and vice versa). The
6814 shallow copy uses a lazy (deferred) copy mechanism that copies the
6815 data only when any changes to the original or shallow copy are made,
6816 ensuring memory efficiency while maintaining data integrity.
6818 .. note::
6819 In pandas versions prior to 3.0, the default behavior without
6820 Copy-on-Write was different: changes to the original *were* reflected
6821 in the shallow copy (and vice versa). See the :ref:`Copy-on-Write
6822 user guide <copy_on_write>` for more information.
6824 Parameters
6825 ----------
6826 deep : bool, default True
6827 Make a deep copy, including a copy of the data and the indices.
6828 With ``deep=False`` neither the indices nor the data are copied.
6830 Returns
6831 -------
6832 Series or DataFrame
6833 Object type matches caller.
6835 See Also
6836 --------
6837 copy.copy : Return a shallow copy of an object.
6838 copy.deepcopy : Return a deep copy of an object.
6840 Notes
6841 -----
6842 When ``deep=True``, data is copied but actual Python objects
6843 will not be copied recursively, only the reference to the object.
6844 This is in contrast to :py:func:`copy.deepcopy` in the Standard Library,
6845 which recursively copies object data (see examples below).
6847 While ``Index`` objects are copied when ``deep=True``, the underlying
6848 numpy array is not copied for performance reasons. Since ``Index`` is
6849 immutable, the underlying data can be safely shared and a copy
6850 is not needed.
6852 Since pandas is not thread safe, see the
6853 :ref:`gotchas <gotchas.thread-safety>` when copying in a threading
6854 environment.
6856 Copy-on-Write protects shallow copies against accidental modifications.
6857 This means that any changes to the copied data would make a new copy
6858 of the data upon write (and vice versa). Changes made to either the
6859 original or copied variable would not be reflected in the counterpart.
6860 See :ref:`Copy_on_Write <copy_on_write>` for more information.
6862 Examples
6863 --------
6864 >>> s = pd.Series([1, 2], index=["a", "b"])
6865 >>> s
6866 a 1
6867 b 2
6868 dtype: int64
6870 >>> s_copy = s.copy(deep=True)
6871 >>> s_copy
6872 a 1
6873 b 2
6874 dtype: int64
6876 Due to Copy-on-Write, shallow copies still protect data modifications.
6877 Note shallow does not get modified below.
6879 >>> s = pd.Series([1, 2], index=["a", "b"])
6880 >>> shallow = s.copy(deep=False)
6881 >>> s.iloc[1] = 200
6882 >>> shallow
6883 a 1
6884 b 2
6885 dtype: int64
6887 When the data has object dtype, even a deep copy does not copy the
6888 underlying Python objects. Updating a nested data object will be
6889 reflected in the deep copy.
6891 >>> s = pd.Series([[1, 2], [3, 4]])
6892 >>> deep = s.copy()
6893 >>> s[0][0] = 10
6894 >>> s
6895 0 [10, 2]
6896 1 [3, 4]
6897 dtype: object
6898 >>> deep
6899 0 [10, 2]
6900 1 [3, 4]
6901 dtype: object
6902 """
6903 data = self._mgr.copy(deep=deep)
6904 return self._constructor_from_mgr(data, axes=data.axes).__finalize__(
6905 self, method="copy"
6906 )
6908 @final
6909 def __copy__(self) -> Self:
6910 return self.copy(deep=False)
6912 @final
6913 def __deepcopy__(self, memo=None) -> Self:
6914 """
6915 Parameters
6916 ----------
6917 memo, default None
6918 Standard signature. Unused
6919 """
6920 return self.copy(deep=True)
6922 @final
6923 def infer_objects(self, copy: bool | lib.NoDefault = lib.no_default) -> Self:
6924 """
6925 Attempt to infer better dtypes for object columns.
6927 Attempts soft conversion of object-dtyped
6928 columns, leaving non-object and unconvertible
6929 columns unchanged. The inference rules are the
6930 same as during normal Series/DataFrame construction.
6932 Parameters
6933 ----------
6934 copy : bool, default False
6935 This keyword is now ignored; changing its value will have no
6936 impact on the method.
6938 .. deprecated:: 3.0.0
6940 This keyword is ignored and will be removed in pandas 4.0. Since
6941 pandas 3.0, this method always returns a new object using a lazy
6942 copy mechanism that defers copies until necessary
6943 (Copy-on-Write). See the `user guide on Copy-on-Write
6944 <https://pandas.pydata.org/docs/dev/user_guide/migration.html>`__
6945 for more details.
6947 Returns
6948 -------
6949 same type as input object
6950 Returns an object of the same type as the input object.
6952 See Also
6953 --------
6954 to_datetime : Convert argument to datetime.
6955 to_timedelta : Convert argument to timedelta.
6956 to_numeric : Convert argument to numeric type.
6957 convert_dtypes : Convert argument to best possible dtype.
6959 Examples
6960 --------
6961 >>> df = pd.DataFrame({"A": ["a", 1, 2, 3]})
6962 >>> df = df.iloc[1:]
6963 >>> df
6964 A
6965 1 1
6966 2 2
6967 3 3
6969 >>> df.dtypes
6970 A object
6971 dtype: object
6973 >>> df.infer_objects().dtypes
6974 A int64
6975 dtype: object
6976 """
6977 self._check_copy_deprecation(copy)
6978 new_mgr = self._mgr.convert()
6979 res = self._constructor_from_mgr(new_mgr, axes=new_mgr.axes)
6980 return res.__finalize__(self, method="infer_objects")
6982 @final
6983 def convert_dtypes(
6984 self,
6985 infer_objects: bool | lib.NoDefault = lib.no_default,
6986 convert_string: bool | lib.NoDefault = lib.no_default,
6987 convert_integer: bool | lib.NoDefault = lib.no_default,
6988 convert_boolean: bool | lib.NoDefault = lib.no_default,
6989 convert_floating: bool | lib.NoDefault = lib.no_default,
6990 dtype_backend: DtypeBackend = "numpy_nullable",
6991 ) -> Self:
6992 """
6993 Convert columns from numpy dtypes to the best dtypes that support ``pd.NA``.
6995 This methods converts columns using default NumPy dtypes to nullable
6996 dtypes (using ``pd.NA`` as missing value indicator).
6998 Parameters
6999 ----------
7000 infer_objects : bool, default True
7001 Whether object dtypes should be converted to the best possible types.
7003 .. deprecated:: 3.1.0
7004 The ``infer_objects`` keyword is deprecated and will be removed
7005 in a future version.
7007 convert_string : bool, default True
7008 Whether object dtypes should be converted to ``StringDtype()``.
7010 .. deprecated:: 3.1.0
7011 The ``convert_string`` keyword is deprecated and will be removed
7012 in a future version.
7014 convert_integer : bool, default True
7015 Whether, if possible, conversion can be done to integer extension types.
7017 .. deprecated:: 3.1.0
7018 The ``convert_integer`` keyword is deprecated and will be removed
7019 in a future version.
7021 convert_boolean : bool, defaults True
7022 Whether object dtypes should be converted to ``BooleanDtypes()``.
7024 .. deprecated:: 3.1.0
7025 The ``convert_boolean`` keyword is deprecated and will be removed
7026 in a future version.
7028 convert_floating : bool, defaults True
7029 Whether, if possible, conversion can be done to floating extension types.
7030 If `convert_integer` is also True, preference will be give to integer
7031 dtypes if the floats can be faithfully casted to integers.
7033 .. deprecated:: 3.1.0
7034 The ``convert_floating`` keyword is deprecated and will be removed
7035 in a future version.
7037 dtype_backend : {'numpy_nullable', 'pyarrow'}, default 'numpy_nullable'
7038 Back-end data type applied to the resultant :class:`DataFrame` or
7039 :class:`Series` (still experimental). Behaviour is as follows:
7041 * ``"numpy_nullable"``: returns nullable-dtype-backed
7042 :class:`DataFrame` or :class:`Series`.
7043 * ``"pyarrow"``: returns pyarrow-backed nullable :class:`ArrowDtype`
7044 :class:`DataFrame` or :class:`Series`.
7046 .. versionadded:: 2.0
7048 Returns
7049 -------
7050 Series or DataFrame
7051 Copy of input object with new dtype.
7053 See Also
7054 --------
7055 infer_objects : Infer dtypes of objects.
7056 to_datetime : Convert argument to datetime.
7057 to_timedelta : Convert argument to timedelta.
7058 to_numeric : Convert argument to a numeric type.
7060 Notes
7061 -----
7062 By default, ``convert_dtypes`` will attempt to convert a Series (or each
7063 Series in a DataFrame) to dtypes that support ``pd.NA``.
7065 For object-dtyped columns, if ``infer_objects`` is ``True``, use the inference
7066 rules as during normal Series/DataFrame construction. Then, if possible,
7067 convert to ``StringDtype``, ``BooleanDtype`` or an appropriate integer
7068 or floating extension type, otherwise leave as ``object``.
7070 If the dtype is integer, convert to an appropriate integer extension type.
7072 If the dtype is numeric, and consists of all integers, convert to an
7073 appropriate integer extension type. Otherwise, convert to an
7074 appropriate floating extension type.
7076 In the future, as new dtypes are added that support ``pd.NA``, the results
7077 of this method will change to support those new dtypes.
7079 Examples
7080 --------
7081 >>> df = pd.DataFrame(
7082 ... {
7083 ... "a": pd.Series([1, 2, 3], dtype=np.dtype("int32")),
7084 ... "b": pd.Series(["x", "y", "z"], dtype=np.dtype("O")),
7085 ... "c": pd.Series([True, False, np.nan], dtype=np.dtype("O")),
7086 ... "d": pd.Series(["h", "i", np.nan], dtype=np.dtype("O")),
7087 ... "e": pd.Series([10, np.nan, 20], dtype=np.dtype("float")),
7088 ... "f": pd.Series([np.nan, 100.5, 200], dtype=np.dtype("float")),
7089 ... }
7090 ... )
7092 Start with a DataFrame with default dtypes.
7094 >>> df
7095 a b c d e f
7096 0 1 x True h 10.0 NaN
7097 1 2 y False i NaN 100.5
7098 2 3 z NaN NaN 20.0 200.0
7100 >>> df.dtypes
7101 a int32
7102 b object
7103 c object
7104 d object
7105 e float64
7106 f float64
7107 dtype: object
7109 Convert the DataFrame to use best possible dtypes.
7111 >>> dfn = df.convert_dtypes()
7112 >>> dfn
7113 a b c d e f
7114 0 1 x True h 10 <NA>
7115 1 2 y False i <NA> 100.5
7116 2 3 z <NA> <NA> 20 200.0
7118 >>> dfn.dtypes
7119 a Int32
7120 b string
7121 c boolean
7122 d string
7123 e Int64
7124 f Float64
7125 dtype: object
7127 Start with a Series of strings and missing data represented by ``np.nan``.
7129 >>> s = pd.Series(["a", "b", np.nan])
7130 >>> s
7131 0 a
7132 1 b
7133 2 NaN
7134 dtype: str
7136 Obtain a Series with dtype ``StringDtype``.
7138 >>> s.convert_dtypes()
7139 0 a
7140 1 b
7141 2 <NA>
7142 dtype: string
7143 """
7144 check_dtype_backend(dtype_backend)
7145 deprecated_args = {
7146 "infer_objects": infer_objects,
7147 "convert_string": convert_string,
7148 "convert_integer": convert_integer,
7149 "convert_boolean": convert_boolean,
7150 "convert_floating": convert_floating,
7151 }
7152 for arg_name, arg_val in deprecated_args.items():
7153 if arg_val is not lib.no_default:
7154 warnings.warn(
7155 f"The {arg_name} keyword in {type(self).__name__}."
7156 f"convert_dtypes is deprecated and will be removed in a "
7157 f"future version.",
7158 Pandas4Warning,
7159 stacklevel=find_stack_level(),
7160 )
7162 # Resolve no_default to the current default values (True)
7163 infer_objects = infer_objects if infer_objects is not lib.no_default else True
7164 convert_string = (
7165 convert_string if convert_string is not lib.no_default else True
7166 )
7167 convert_integer = (
7168 convert_integer if convert_integer is not lib.no_default else True
7169 )
7170 convert_boolean = (
7171 convert_boolean if convert_boolean is not lib.no_default else True
7172 )
7173 convert_floating = (
7174 convert_floating if convert_floating is not lib.no_default else True
7175 )
7177 new_mgr = self._mgr.convert_dtypes(
7178 infer_objects=infer_objects,
7179 convert_string=convert_string,
7180 convert_integer=convert_integer,
7181 convert_boolean=convert_boolean,
7182 convert_floating=convert_floating,
7183 dtype_backend=dtype_backend,
7184 )
7185 res = self._constructor_from_mgr(new_mgr, axes=new_mgr.axes)
7186 return res.__finalize__(self, method="convert_dtypes")
7188 # ----------------------------------------------------------------------
7189 # Filling NA's
7191 @final
7192 def _pad_or_backfill(
7193 self,
7194 method: Literal["ffill", "bfill", "pad", "backfill"],
7195 *,
7196 axis: Axis | None = None,
7197 inplace: bool = False,
7198 limit: int | None = None,
7199 limit_area: Literal["inside", "outside"] | None = None,
7200 ):
7201 if axis is None:
7202 axis = 0
7203 axis = self._get_axis_number(axis)
7204 method = clean_fill_method(method)
7206 if axis == 1:
7207 if not self._mgr.is_single_block and inplace:
7208 raise NotImplementedError
7209 # e.g. test_align_fill_method
7210 result = self.T._pad_or_backfill(
7211 method=method, limit=limit, limit_area=limit_area
7212 ).T
7214 return result
7216 new_mgr = self._mgr.pad_or_backfill(
7217 method=method,
7218 limit=limit,
7219 limit_area=limit_area,
7220 inplace=inplace,
7221 )
7222 result = self._constructor_from_mgr(new_mgr, axes=new_mgr.axes)
7223 if inplace:
7224 self._update_inplace(result)
7225 return self
7226 else:
7227 return result.__finalize__(self, method="fillna")
7229 @final
7230 def fillna(
7231 self,
7232 value: Hashable | Mapping | Series | DataFrame,
7233 *,
7234 axis: Axis | None = None,
7235 inplace: bool = False,
7236 limit: int | None = None,
7237 ) -> Self:
7238 """
7239 Fill NA/NaN values with `value`.
7241 This method replaces missing values with a specified value.
7243 Parameters
7244 ----------
7245 value : scalar, dict, Series, or DataFrame
7246 Value to use to fill holes (e.g. 0), alternately a
7247 dict/Series/DataFrame of values specifying which value to use for
7248 each index (for a Series) or column (for a DataFrame). Values not
7249 in the dict/Series/DataFrame will not be filled. This value cannot
7250 be a list.
7251 axis : {0 or 'index'} for Series, {0 or 'index', 1 or 'columns'} for DataFrame
7252 Axis along which to fill missing values. For `Series`
7253 this parameter is unused and defaults to 0.
7254 inplace : bool, default False
7255 If True, fill in-place. Note: this will modify any
7256 other views on this object (e.g., a no-copy slice for a column in a
7257 DataFrame).
7258 limit : int, default None
7259 This is the maximum number of entries along the entire axis
7260 where NaNs will be filled. Must be greater than 0 if not None.
7262 Returns
7263 -------
7264 Series/DataFrame
7265 Object with missing values filled.
7267 See Also
7268 --------
7269 ffill : Fill values by propagating the last valid observation to next valid.
7270 bfill : Fill values by using the next valid observation to fill the gap.
7271 interpolate : Fill NaN values using interpolation.
7272 reindex : Conform object to new index.
7273 asfreq : Convert TimeSeries to specified frequency.
7275 Notes
7276 -----
7277 For non-object dtype, ``value=None`` will use the NA value of the dtype.
7278 See more details in the :ref:`Filling missing data<missing_data.fillna>`
7279 section.
7281 Examples
7282 --------
7283 >>> df = pd.DataFrame(
7284 ... [
7285 ... [np.nan, 2, np.nan, 0],
7286 ... [3, 4, np.nan, 1],
7287 ... [np.nan, np.nan, np.nan, np.nan],
7288 ... [np.nan, 3, np.nan, 4],
7289 ... ],
7290 ... columns=list("ABCD"),
7291 ... )
7292 >>> df
7293 A B C D
7294 0 NaN 2.0 NaN 0.0
7295 1 3.0 4.0 NaN 1.0
7296 2 NaN NaN NaN NaN
7297 3 NaN 3.0 NaN 4.0
7299 Replace all NaN elements with 0s.
7301 >>> df.fillna(0)
7302 A B C D
7303 0 0.0 2.0 0.0 0.0
7304 1 3.0 4.0 0.0 1.0
7305 2 0.0 0.0 0.0 0.0
7306 3 0.0 3.0 0.0 4.0
7308 Replace all NaN elements in column 'A', 'B', 'C', and 'D', with 0, 1,
7309 2, and 3 respectively.
7311 >>> values = {"A": 0, "B": 1, "C": 2, "D": 3}
7312 >>> df.fillna(value=values)
7313 A B C D
7314 0 0.0 2.0 2.0 0.0
7315 1 3.0 4.0 2.0 1.0
7316 2 0.0 1.0 2.0 3.0
7317 3 0.0 3.0 2.0 4.0
7319 Only replace the first NaN element.
7321 >>> df.fillna(value=values, limit=1)
7322 A B C D
7323 0 0.0 2.0 2.0 0.0
7324 1 3.0 4.0 NaN 1.0
7325 2 NaN 1.0 NaN 3.0
7326 3 NaN 3.0 NaN 4.0
7328 When filling using a DataFrame, replacement happens along
7329 the same column names and same indices
7331 >>> df2 = pd.DataFrame(np.zeros((4, 4)), columns=list("ABCE"))
7332 >>> df.fillna(df2)
7333 A B C D
7334 0 0.0 2.0 0.0 0.0
7335 1 3.0 4.0 0.0 1.0
7336 2 0.0 0.0 0.0 NaN
7337 3 0.0 3.0 0.0 4.0
7339 Note that column D is not affected since it is not present in df2.
7340 """
7341 inplace = validate_bool_kwarg(inplace, "inplace")
7342 if inplace:
7343 if not CHAINED_WARNING_DISABLED:
7344 if sys.getrefcount(
7345 self
7346 ) <= REF_COUNT_METHOD and not common.is_local_in_caller_frame(self):
7347 warnings.warn(
7348 _chained_assignment_method_msg,
7349 ChainedAssignmentError,
7350 stacklevel=2,
7351 )
7353 if isinstance(value, (list, tuple)):
7354 raise TypeError(
7355 '"value" parameter must be a scalar or dict, but '
7356 f'you passed a "{type(value).__name__}"'
7357 )
7359 # set the default here, so functions examining the signature
7360 # can detect if something was set (e.g. in groupby) (GH9221)
7361 if axis is None:
7362 axis = 0
7363 axis = self._get_axis_number(axis)
7365 if self.ndim == 1:
7366 if isinstance(value, (dict, ABCSeries)):
7367 if not len(value):
7368 # test_fillna_nonscalar
7369 return self if inplace else self.copy(deep=False)
7370 from pandas import Series
7372 value = Series(value)
7373 value = value.reindex(self.index)
7374 value = value._values
7375 elif not is_list_like(value):
7376 pass
7377 else:
7378 raise TypeError(
7379 '"value" parameter must be a scalar, dict '
7380 "or Series, but you passed a "
7381 f'"{type(value).__name__}"'
7382 )
7384 new_data = self._mgr.fillna(value=value, limit=limit, inplace=inplace)
7386 elif isinstance(value, (dict, ABCSeries)):
7387 result = self if inplace else self.copy(deep=False)
7388 if axis == 1:
7389 # Check that all columns in result have the same dtype
7390 # otherwise don't bother with fillna and losing accurate dtypes
7391 unique_dtypes = self._mgr.get_unique_dtypes()
7392 if len(unique_dtypes) > 1:
7393 raise ValueError(
7394 "All columns must have the same dtype, but got dtypes: "
7395 f"{list(unique_dtypes)}"
7396 )
7397 # Use the first column, which we have already validated has the
7398 # same dtypes as the other columns.
7399 if not can_hold_element(result.iloc[:, 0], value):
7400 frame_dtype = unique_dtypes.item()
7401 raise ValueError(
7402 f"{value} not a suitable type to fill into {frame_dtype}"
7403 )
7404 result = result.T.fillna(value=value).T
7405 if inplace:
7406 self._update_inplace(result)
7407 result = self
7408 else:
7409 for k, v in value.items():
7410 if k not in result:
7411 continue
7413 res_k = result[k].fillna(v, limit=limit)
7415 if not inplace:
7416 result[k] = res_k
7417 # We can write into our existing column(s) iff dtype
7418 # was preserved.
7419 elif isinstance(res_k, ABCSeries):
7420 # i.e. 'k' only shows up once in self.columns
7421 if res_k.dtype == result[k].dtype:
7422 result.loc[:, k] = res_k
7423 else:
7424 # Different dtype -> no way to do inplace.
7425 result[k] = res_k
7426 else:
7427 # see test_fillna_dict_inplace_nonunique_columns
7428 locs = result.columns.get_loc(k)
7429 if isinstance(locs, slice):
7430 locs = range(self.shape[1])[locs]
7431 elif isinstance(locs, np.ndarray) and locs.dtype.kind == "b":
7432 locs = locs.nonzero()[0]
7433 elif not (
7434 isinstance(locs, np.ndarray) and locs.dtype.kind == "i"
7435 ):
7436 # Should never be reached, but let's cover our bases
7437 raise NotImplementedError(
7438 "Unexpected get_loc result, please report a bug at "
7439 "https://github.com/pandas-dev/pandas"
7440 )
7442 for i, loc in enumerate(locs):
7443 res_loc = res_k.iloc[:, i]
7444 target = self.iloc[:, loc]
7446 if res_loc.dtype == target.dtype:
7447 result.iloc[:, loc] = res_loc
7448 else:
7449 result.isetitem(loc, res_loc)
7450 return result
7452 elif not is_list_like(value):
7453 if axis == 1:
7454 result = self.T.fillna(value=value, limit=limit).T
7455 new_data = result._mgr
7456 else:
7457 new_data = self._mgr.fillna(value=value, limit=limit, inplace=inplace)
7458 elif isinstance(value, ABCDataFrame) and self.ndim == 2:
7459 new_data = self.where(self.notna(), value)._mgr
7460 else:
7461 raise ValueError(
7462 "Invalid fill value: expected scalar, dict, Series or DataFrame; "
7463 f"got {type(value).__name__}"
7464 )
7466 result = self._constructor_from_mgr(new_data, axes=new_data.axes)
7467 if inplace:
7468 self._update_inplace(result)
7469 return self
7470 else:
7471 return result.__finalize__(self, method="fillna")
7473 @final
7474 def ffill(
7475 self,
7476 *,
7477 axis: Axis | None = None,
7478 inplace: bool = False,
7479 limit: int | None = None,
7480 limit_area: Literal["inside", "outside"] | None = None,
7481 ) -> Self:
7482 """
7483 Fill NA/NaN values by propagating the last valid observation to next valid.
7485 This method fills missing values using forward fill, where the last
7486 valid observation is propagated forward to fill the gaps.
7488 Parameters
7489 ----------
7490 axis : {0 or 'index'} for Series, {0 or 'index', 1 or 'columns'} for DataFrame
7491 Axis along which to fill missing values. For `Series`
7492 this parameter is unused and defaults to 0.
7493 inplace : bool, default False
7494 If True, fill in-place. Note: this will modify any
7495 other views on this object (e.g., a no-copy slice for a column in a
7496 DataFrame).
7497 limit : int, default None
7498 Maximum number of consecutive NaN values to fill. In other words, if
7499 there is a gap with more than this number of consecutive NaNs, it
7500 will only be partially filled. Must be greater than 0 if not None.
7501 limit_area : {`None`, 'inside', 'outside'}, default None
7502 Restrict which NaNs are filled based on their position relative to
7503 the valid values.
7505 * ``None``: No fill restriction.
7506 * 'inside': Only fill NaNs surrounded by valid values
7507 (interpolate).
7508 * 'outside': Only fill NaNs outside valid values (extrapolate).
7510 .. versionadded:: 2.2.0
7512 Returns
7513 -------
7514 Series/DataFrame
7515 Object with missing values filled.
7517 See Also
7518 --------
7519 DataFrame.bfill : Fill NA/NaN values by using the next valid observation
7520 to fill the gap.
7522 Examples
7523 --------
7524 >>> df = pd.DataFrame(
7525 ... [
7526 ... [np.nan, 2, np.nan, 0],
7527 ... [3, 4, np.nan, 1],
7528 ... [np.nan, np.nan, np.nan, np.nan],
7529 ... [np.nan, 3, np.nan, 4],
7530 ... ],
7531 ... columns=list("ABCD"),
7532 ... )
7533 >>> df
7534 A B C D
7535 0 NaN 2.0 NaN 0.0
7536 1 3.0 4.0 NaN 1.0
7537 2 NaN NaN NaN NaN
7538 3 NaN 3.0 NaN 4.0
7540 >>> df.ffill()
7541 A B C D
7542 0 NaN 2.0 NaN 0.0
7543 1 3.0 4.0 NaN 1.0
7544 2 3.0 4.0 NaN 1.0
7545 3 3.0 3.0 NaN 4.0
7547 >>> ser = pd.Series([1, np.nan, 2, 3])
7548 >>> ser.ffill()
7549 0 1.0
7550 1 1.0
7551 2 2.0
7552 3 3.0
7553 dtype: float64
7554 """
7555 inplace = validate_bool_kwarg(inplace, "inplace")
7556 if inplace:
7557 if not CHAINED_WARNING_DISABLED:
7558 if sys.getrefcount(
7559 self
7560 ) <= REF_COUNT_METHOD and not common.is_local_in_caller_frame(self):
7561 warnings.warn(
7562 _chained_assignment_method_msg,
7563 ChainedAssignmentError,
7564 stacklevel=2,
7565 )
7567 return self._pad_or_backfill(
7568 "ffill",
7569 axis=axis,
7570 inplace=inplace,
7571 limit=limit,
7572 limit_area=limit_area,
7573 )
7575 @final
7576 def bfill(
7577 self,
7578 *,
7579 axis: Axis | None = None,
7580 inplace: bool = False,
7581 limit: int | None = None,
7582 limit_area: Literal["inside", "outside"] | None = None,
7583 ) -> Self:
7584 """
7585 Fill NA/NaN values by using the next valid observation to fill the gap.
7587 This method fills missing values in a backward direction along the
7588 specified axis, propagating non-null values from later positions to
7589 earlier positions containing NaN.
7591 Parameters
7592 ----------
7593 axis : {0 or 'index'} for Series, {0 or 'index', 1 or 'columns'} for DataFrame
7594 Axis along which to fill missing values. For `Series`
7595 this parameter is unused and defaults to 0.
7596 inplace : bool, default False
7597 If True, fill in-place. Note: this will modify any
7598 other views on this object (e.g., a no-copy slice for a column in a
7599 DataFrame).
7600 limit : int, default None
7601 Maximum number of consecutive NaN values to fill. In other words, if
7602 there is a gap with more than this number of consecutive NaNs, it
7603 will only be partially filled. Must be greater than 0 if not None.
7604 limit_area : {`None`, 'inside', 'outside'}, default None
7605 Restrict which NaNs are filled based on their position relative to
7606 the valid values.
7608 * ``None``: No fill restriction.
7609 * 'inside': Only fill NaNs surrounded by valid values
7610 (interpolate).
7611 * 'outside': Only fill NaNs outside valid values (extrapolate).
7613 .. versionadded:: 2.2.0
7615 Returns
7616 -------
7617 Series/DataFrame
7618 Object with missing values filled.
7620 See Also
7621 --------
7622 DataFrame.ffill : Fill NA/NaN values by propagating the last valid
7623 observation to next valid.
7625 Examples
7626 --------
7627 For Series:
7629 >>> s = pd.Series([1, None, None, 2])
7630 >>> s.bfill()
7631 0 1.0
7632 1 2.0
7633 2 2.0
7634 3 2.0
7635 dtype: float64
7636 >>> s.bfill(limit=1)
7637 0 1.0
7638 1 NaN
7639 2 2.0
7640 3 2.0
7641 dtype: float64
7643 With DataFrame:
7645 >>> df = pd.DataFrame({"A": [1, None, None, 4], "B": [None, 5, None, 7]})
7646 >>> df
7647 A B
7648 0 1.0 NaN
7649 1 NaN 5.0
7650 2 NaN NaN
7651 3 4.0 7.0
7652 >>> df.bfill()
7653 A B
7654 0 1.0 5.0
7655 1 4.0 5.0
7656 2 4.0 7.0
7657 3 4.0 7.0
7658 >>> df.bfill(limit=1)
7659 A B
7660 0 1.0 5.0
7661 1 NaN 5.0
7662 2 4.0 7.0
7663 3 4.0 7.0
7664 """
7665 inplace = validate_bool_kwarg(inplace, "inplace")
7666 if inplace:
7667 if not CHAINED_WARNING_DISABLED:
7668 if sys.getrefcount(
7669 self
7670 ) <= REF_COUNT_METHOD and not common.is_local_in_caller_frame(self):
7671 warnings.warn(
7672 _chained_assignment_method_msg,
7673 ChainedAssignmentError,
7674 stacklevel=2,
7675 )
7677 return self._pad_or_backfill(
7678 "bfill",
7679 axis=axis,
7680 inplace=inplace,
7681 limit=limit,
7682 limit_area=limit_area,
7683 )
7685 @final
7686 def replace(
7687 self,
7688 to_replace=None,
7689 value=lib.no_default,
7690 *,
7691 inplace: bool = False,
7692 regex: bool = False,
7693 ) -> Self:
7694 """
7695 Replace values given in `to_replace` with `value`.
7697 Values of the Series/DataFrame are replaced with other values dynamically.
7698 This differs from updating with ``.loc`` or ``.iloc``, which require
7699 you to specify a location to update with some value.
7701 Parameters
7702 ----------
7703 to_replace : str, regex, list, dict, Series, int, float, or None
7704 How to find the values that will be replaced.
7706 * numeric, str or regex:
7708 - numeric: numeric values equal to `to_replace` will be
7709 replaced with `value`
7710 - str: string exactly matching `to_replace` will be replaced
7711 with `value`
7712 - regex: regexes matching `to_replace` will be replaced with
7713 `value`
7715 * list of str, regex, or numeric:
7717 - First, if `to_replace` and `value` are both lists, they
7718 **must** be the same length.
7719 - Second, if ``regex=True`` then all of the strings in **both**
7720 lists will be interpreted as regexes otherwise they will match
7721 directly. This doesn't matter much for `value` since there
7722 are only a few possible substitution regexes you can use.
7723 - str, regex and numeric rules apply as above.
7725 * dict:
7727 - Dicts can be used to specify different replacement values
7728 for different existing values. For example,
7729 ``{'a': 'b', 'y': 'z'}`` replaces the value 'a' with 'b' and
7730 'y' with 'z'. To use a dict in this way, the optional `value`
7731 parameter should not be given.
7732 - For a DataFrame a dict can specify that different values
7733 should be replaced in different columns. For example,
7734 ``{'a': 1, 'b': 'z'}`` looks for the value 1 in column 'a'
7735 and the value 'z' in column 'b' and replaces these values
7736 with whatever is specified in `value`. The `value` parameter
7737 should not be ``None`` in this case. You can treat this as a
7738 special case of passing two lists except that you are
7739 specifying the column to search in.
7740 - For a DataFrame nested dictionaries, e.g.,
7741 ``{'a': {'b': np.nan}}``, are read as follows: look in column
7742 'a' for the value 'b' and replace it with NaN. The optional `value`
7743 parameter should not be specified to use a nested dict in this
7744 way. You can nest regular expressions as well. Note that
7745 column names (the top-level dictionary keys in a nested
7746 dictionary) **cannot** be regular expressions.
7748 * None:
7750 - This means that the `regex` argument must be a string,
7751 compiled regular expression, or list, dict, ndarray or
7752 Series of such elements. If `value` is also ``None`` then
7753 this **must** be a nested dictionary or Series.
7755 See the examples section for examples of each of these.
7756 value : scalar, dict, list, str, regex, default None
7757 Value to replace any values matching `to_replace` with.
7758 For a DataFrame a dict of values can be used to specify which
7759 value to use for each column (columns not in the dict will not be
7760 filled). Regular expressions, strings and lists or dicts of such
7761 objects are also allowed.
7763 inplace : bool, default False
7764 If True, performs operation inplace.
7765 regex : bool or same types as `to_replace`, default False
7766 Whether to interpret `to_replace` and/or `value` as regular
7767 expressions. Alternatively, this could be a regular expression or a
7768 list, dict, or array of regular expressions in which case
7769 `to_replace` must be ``None``. Patterns may be passed either as
7770 strings or as compiled regex objects (``re.compile(...)``); use a
7771 compiled object when you need to set flags such as ``re.IGNORECASE``,
7772 since ``replace`` does not accept a separate ``flags`` argument.
7774 Returns
7775 -------
7776 Series/DataFrame
7777 Object after replacement.
7779 Raises
7780 ------
7781 AssertionError
7782 * If `regex` is not a ``bool`` and `to_replace` is not
7783 ``None``.
7785 TypeError
7786 * If `to_replace` is not a scalar, array-like, ``dict``, or ``None``
7787 * If `to_replace` is a ``dict`` and `value` is not a ``list``,
7788 ``dict``, ``ndarray``, or ``Series``
7789 * If `to_replace` is ``None`` and `regex` is not compilable
7790 into a regular expression or is a list, dict, ndarray, or
7791 Series.
7792 * When replacing multiple ``bool`` or ``datetime64`` objects and
7793 the arguments to `to_replace` does not match the type of the
7794 value being replaced
7796 ValueError
7797 * If a ``list`` or an ``ndarray`` is passed to `to_replace` and
7798 `value` but they are not the same length.
7800 See Also
7801 --------
7802 Series.fillna : Fill NA values.
7803 DataFrame.fillna : Fill NA values.
7804 Series.where : Replace values based on boolean condition.
7805 DataFrame.where : Replace values based on boolean condition.
7806 DataFrame.map: Apply a function to a Dataframe elementwise.
7807 Series.map: Map values of Series according to an input mapping or function.
7808 Series.str.replace : Simple string replacement.
7810 Notes
7811 -----
7812 * Regex substitution is performed under the hood with ``re.sub``. The
7813 rules for substitution for ``re.sub`` are the same.
7814 * Regular expressions will only substitute on strings, meaning you
7815 cannot provide, for example, a regular expression matching floating
7816 point numbers and expect the columns in your frame that have a
7817 numeric dtype to be matched. However, if those floating point
7818 numbers *are* strings, then you can do this.
7819 * This method has *a lot* of options. You are encouraged to experiment
7820 and play with this method to gain intuition about how it works.
7821 * When dict is used as the `to_replace` value, it is like
7822 key(s) in the dict are the to_replace part and
7823 value(s) in the dict are the value parameter.
7824 * Unless `regex` is True, a key matches only if it equals the entire
7825 value, not a substring of it: ``{"b": "z"}`` replaces the value ``"b"``
7826 but leaves ``"a b c"`` unchanged.
7827 * Dict entries are applied one after another, in insertion order. Which
7828 entries apply to an element is decided up front by matching every key
7829 against the original value, but each substitution is made into the
7830 result of the previous ones. An entry can therefore end up a no-op if
7831 an earlier one already rewrote the text it targeted: with
7832 ``regex=True``, ``{"x": "1", "x y": "2"}`` turns ``"x y"`` into
7833 ``"1 y"``, while ``{"x y": "2", "x": "1"}`` turns it into ``"2"``.
7834 Conversely, a later entry can rewrite what an earlier one produced:
7835 ``{"ab": "ba", "ba": "zz"}`` turns ``"ab ba"`` into ``"zz zz"``.
7836 With overlapping keys, order the dict most-specific-first.
7837 * Replacement is based on equality, not identity. Since Python treats
7838 ``True == 1`` and ``False == 0``, replacing one will also affect
7839 the other when they share a dtype (e.g. ``object``).
7841 Examples
7842 --------
7844 **Scalar `to_replace` and `value`**
7846 >>> s = pd.Series([1, 2, 3, 4, 5])
7847 >>> s.replace(1, 5)
7848 0 5
7849 1 2
7850 2 3
7851 3 4
7852 4 5
7853 dtype: int64
7855 >>> df = pd.DataFrame(
7856 ... {
7857 ... "A": [0, 1, 2, 3, 4],
7858 ... "B": [5, 6, 7, 8, 9],
7859 ... "C": ["a", "b", "c", "d", "e"],
7860 ... }
7861 ... )
7862 >>> df.replace(0, 5)
7863 A B C
7864 0 5 5 a
7865 1 1 6 b
7866 2 2 7 c
7867 3 3 8 d
7868 4 4 9 e
7870 **List-like `to_replace`**
7872 >>> df.replace([0, 1, 2, 3], 4)
7873 A B C
7874 0 4 5 a
7875 1 4 6 b
7876 2 4 7 c
7877 3 4 8 d
7878 4 4 9 e
7880 >>> df.replace([0, 1, 2, 3], [4, 3, 2, 1])
7881 A B C
7882 0 4 5 a
7883 1 3 6 b
7884 2 2 7 c
7885 3 1 8 d
7886 4 4 9 e
7888 **dict-like `to_replace`**
7890 >>> df.replace({0: 10, 1: 100})
7891 A B C
7892 0 10 5 a
7893 1 100 6 b
7894 2 2 7 c
7895 3 3 8 d
7896 4 4 9 e
7898 >>> df.replace({"A": 0, "B": 5}, 100)
7899 A B C
7900 0 100 100 a
7901 1 1 6 b
7902 2 2 7 c
7903 3 3 8 d
7904 4 4 9 e
7906 >>> df.replace({"A": {0: 100, 4: 400}})
7907 A B C
7908 0 100 5 a
7909 1 1 6 b
7910 2 2 7 c
7911 3 3 8 d
7912 4 400 9 e
7914 **Regular expression `to_replace`**
7916 >>> df = pd.DataFrame({"A": ["bat", "foo", "bait"], "B": ["abc", "bar", "xyz"]})
7917 >>> df.replace(to_replace=r"^ba.$", value="new", regex=True)
7918 A B
7919 0 new abc
7920 1 foo new
7921 2 bait xyz
7923 >>> df.replace({"A": r"^ba.$"}, {"A": "new"}, regex=True)
7924 A B
7925 0 new abc
7926 1 foo bar
7927 2 bait xyz
7929 >>> df.replace(regex=r"^ba.$", value="new")
7930 A B
7931 0 new abc
7932 1 foo new
7933 2 bait xyz
7935 >>> df.replace(regex={r"^ba.$": "new", "foo": "xyz"})
7936 A B
7937 0 new abc
7938 1 xyz new
7939 2 bait xyz
7941 >>> df.replace(regex=[r"^ba.$", "foo"], value="new")
7942 A B
7943 0 new abc
7944 1 new new
7945 2 bait xyz
7947 To match case-insensitively (or apply any other ``re`` flag), pass a
7948 compiled regex object. ``replace`` does not take a separate ``flags``
7949 argument, so the flags must be baked into the compiled pattern:
7951 >>> import re
7952 >>> df = pd.DataFrame({"A": ["Foo", "FOO", "bar"], "B": ["foo", "Bar", "BAR"]})
7953 >>> df.replace(re.compile(r"foo", flags=re.IGNORECASE), "new", regex=True)
7954 A B
7955 0 new new
7956 1 new Bar
7957 2 bar BAR
7959 Compare the behavior of ``s.replace({'a': None})`` and
7960 ``s.replace('a', None)`` to understand the peculiarities
7961 of the `to_replace` parameter:
7963 >>> s = pd.Series([10, "a", "a", "b", "a"])
7965 When one uses a dict as the `to_replace` value, it is like the
7966 value(s) in the dict are equal to the `value` parameter.
7967 ``s.replace({'a': None})`` is equivalent to
7968 ``s.replace(to_replace={'a': None}, value=None)``:
7970 >>> s.replace({"a": None})
7971 0 10
7972 1 None
7973 2 None
7974 3 b
7975 4 None
7976 dtype: object
7978 If ``None`` is explicitly passed for ``value``, it will be respected:
7980 >>> s.replace("a", None)
7981 0 10
7982 1 None
7983 2 None
7984 3 b
7985 4 None
7986 dtype: object
7988 When ``regex=True``, ``value`` is not ``None`` and `to_replace` is a string,
7989 the replacement will be applied in all columns of the DataFrame.
7991 >>> df = pd.DataFrame(
7992 ... {
7993 ... "A": [0, 1, 2, 3, 4],
7994 ... "B": ["a", "b", "c", "d", "e"],
7995 ... "C": ["f", "g", "h", "i", "j"],
7996 ... }
7997 ... )
7999 >>> df.replace(to_replace="^[a-g]", value="e", regex=True)
8000 A B C
8001 0 0 e e
8002 1 1 e e
8003 2 2 e h
8004 3 3 e i
8005 4 4 e j
8007 If ``value`` is not ``None`` and `to_replace` is a dictionary, the dictionary
8008 keys will be the DataFrame columns that the replacement will be applied.
8010 >>> df.replace(to_replace={"B": "^[a-c]", "C": "^[h-j]"}, value="e", regex=True)
8011 A B C
8012 0 0 e f
8013 1 1 e g
8014 2 2 e e
8015 3 3 d e
8016 4 4 e e
8017 """
8018 if not is_bool(regex) and to_replace is not None:
8019 raise ValueError("'to_replace' must be 'None' if 'regex' is not a bool")
8021 if callable(to_replace):
8022 raise TypeError(
8023 "Expecting 'to_replace' to be either a scalar, array-like, "
8024 "dict or None, got invalid type "
8025 f"{type(to_replace).__name__!r}"
8026 )
8028 if value is lib.no_default and not (
8029 is_dict_like(to_replace) or is_dict_like(regex)
8030 ):
8031 raise ValueError(
8032 # GH#33302
8033 f"{type(self).__name__}.replace must specify either 'value', "
8034 "a dict-like 'to_replace', or dict-like 'regex'."
8035 )
8037 inplace = validate_bool_kwarg(inplace, "inplace")
8038 if inplace:
8039 if not CHAINED_WARNING_DISABLED:
8040 if sys.getrefcount(
8041 self
8042 ) <= REF_COUNT_METHOD and not common.is_local_in_caller_frame(self):
8043 warnings.warn(
8044 _chained_assignment_method_msg,
8045 ChainedAssignmentError,
8046 stacklevel=2,
8047 )
8049 if value is lib.no_default:
8050 if not is_dict_like(to_replace):
8051 # In this case we have checked above that
8052 # 1) regex is dict-like and 2) to_replace is None
8053 to_replace = regex
8054 regex = True
8056 items = list(to_replace.items())
8057 if items:
8058 keys, values = zip(*items, strict=True)
8059 else:
8060 keys, values = ([], []) # type: ignore[assignment]
8062 are_mappings = [is_dict_like(v) for v in values]
8064 if any(are_mappings):
8065 if not all(are_mappings):
8066 raise TypeError(
8067 "If a nested mapping is passed, all values "
8068 "of the top level mapping must be mappings"
8069 )
8070 # passed a nested dict/Series
8071 to_rep_dict = {}
8072 value_dict = {}
8074 for k, v in items:
8075 # error: Incompatible types in assignment (expression has type
8076 # "list[Never]", variable has type "tuple[Any, ...]")
8077 keys, values = list(zip(*v.items(), strict=True)) or ( # type: ignore[assignment]
8078 [],
8079 [],
8080 )
8082 to_rep_dict[k] = list(keys)
8083 value_dict[k] = list(values)
8085 to_replace, value = to_rep_dict, value_dict
8086 else:
8087 to_replace, value = keys, values
8089 return self.replace(to_replace, value, inplace=inplace, regex=regex)
8090 else:
8091 # need a non-zero len on all axes
8092 if not self.size:
8093 return self if inplace else self.copy(deep=False)
8094 if is_dict_like(to_replace):
8095 if is_dict_like(value): # {'A' : NA} -> {'A' : 0}
8096 if isinstance(self, ABCSeries):
8097 raise ValueError(
8098 "to_replace and value cannot be dict-like for "
8099 "Series.replace"
8100 )
8101 # Note: Checking below for `in foo.keys()` instead of
8102 # `in foo` is needed for when we have a Series and not dict
8103 mapping = {
8104 col: (
8105 to_replace[col], # pyright: ignore[reportOptionalSubscript]
8106 value[col],
8107 )
8108 for col in to_replace.keys()
8109 if col in value.keys() and col in self
8110 }
8111 return self._replace_columnwise(mapping, inplace, regex)
8113 # {'A': NA} -> 0
8114 elif not is_list_like(value):
8115 # Operate column-wise
8116 if self.ndim == 1:
8117 raise ValueError(
8118 "Series.replace cannot specify both a dict-like "
8119 "'to_replace' and a 'value'"
8120 )
8121 mapping = {
8122 col: (to_rep, value) for col, to_rep in to_replace.items()
8123 }
8124 return self._replace_columnwise(mapping, inplace, regex)
8125 else:
8126 raise TypeError("value argument must be scalar, dict, or Series")
8128 elif is_list_like(to_replace):
8129 if not is_list_like(value):
8130 # e.g. to_replace = [NA, ''] and value is 0,
8131 # so we replace NA with 0 and then replace '' with 0
8132 value = [value] * len(to_replace)
8134 # e.g. we have to_replace = [NA, ''] and value = [0, 'missing']
8135 if len(to_replace) != len(value):
8136 raise ValueError(
8137 f"Replacement lists must match in length. "
8138 f"Expecting {len(to_replace)} got {len(value)} "
8139 )
8140 new_data = self._mgr.replace_list(
8141 src_list=to_replace,
8142 dest_list=value,
8143 inplace=inplace,
8144 regex=regex,
8145 )
8147 elif to_replace is None:
8148 if not (
8149 is_re_compilable(regex)
8150 or is_list_like(regex)
8151 or is_dict_like(regex)
8152 ):
8153 raise TypeError(
8154 f"'regex' must be a string or a compiled regular expression "
8155 f"or a list or dict of strings or regular expressions, "
8156 f"you passed a {type(regex).__name__!r}"
8157 )
8158 return self.replace(regex, value, inplace=inplace, regex=True)
8159 # dest iterable dict-like
8160 elif is_dict_like(value): # NA -> {'A' : 0, 'B' : -1}
8161 # Operate column-wise
8162 if self.ndim == 1:
8163 raise ValueError(
8164 "Series.replace cannot use dict-value and non-None to_replace"
8165 )
8166 mapping = {col: (to_replace, val) for col, val in value.items()}
8167 return self._replace_columnwise(mapping, inplace, regex)
8169 elif not is_list_like(value): # NA -> 0
8170 regex = should_use_regex(regex, to_replace)
8171 if regex:
8172 new_data = self._mgr.replace_regex(
8173 to_replace=to_replace,
8174 value=value,
8175 inplace=inplace,
8176 )
8177 else:
8178 new_data = self._mgr.replace(
8179 to_replace=to_replace, value=value, inplace=inplace
8180 )
8181 else:
8182 raise TypeError(
8183 f'Invalid "to_replace" type: {type(to_replace).__name__!r}'
8184 )
8186 result = self._constructor_from_mgr(new_data, axes=new_data.axes)
8187 if inplace:
8188 self._update_inplace(result)
8189 return self
8190 else:
8191 return result.__finalize__(self, method="replace")
8193 @final
8194 def interpolate(
8195 self,
8196 method: InterpolateOptions = "linear",
8197 *,
8198 axis: Axis = 0,
8199 limit: int | None = None,
8200 inplace: bool = False,
8201 limit_direction: Literal["forward", "backward", "both"] | None = None,
8202 limit_area: Literal["inside", "outside"] | None = None,
8203 **kwargs,
8204 ) -> Self:
8205 """
8206 Fill NaN values using an interpolation method.
8208 Please note that only ``method='linear'`` is supported for
8209 DataFrame/Series with a MultiIndex.
8211 Parameters
8212 ----------
8213 method : str, default 'linear'
8214 Interpolation technique to use. One of:
8216 * 'linear': Ignore the index and treat the values as equally
8217 spaced. This is the only method supported on MultiIndexes.
8218 * 'time': Works on daily and higher resolution data to interpolate
8219 given length of interval. This interpolates values based on
8220 time interval between observations.
8221 * 'index': The interpolation uses the numerical values
8222 of the DataFrame's index to linearly calculate missing values.
8223 * 'values': Interpolation based on the numerical values
8224 in the DataFrame, treating them as equally spaced along the index.
8225 * 'nearest', 'zero', 'slinear', 'quadratic', 'cubic',
8226 'barycentric', 'polynomial': Passed to
8227 `scipy.interpolate.interp1d`, whereas 'spline' is passed to
8228 `scipy.interpolate.UnivariateSpline`. These methods use the numerical
8229 values of the index. Both 'polynomial' and 'spline' require that
8230 you also specify an `order` (int), e.g.
8231 ``df.interpolate(method='polynomial', order=5)``. Note that,
8232 `slinear` method in Pandas refers to the Scipy first order `spline`
8233 instead of Pandas first order `spline`.
8234 * 'krogh', 'piecewise_polynomial', 'spline', 'pchip', 'akima',
8235 'cubicspline': Wrappers around the SciPy interpolation methods of
8236 similar names. See `Notes`.
8237 * 'from_derivatives': Refers to
8238 `scipy.interpolate.BPoly.from_derivatives`.
8240 axis : {0 or 'index', 1 or 'columns', None}, default None
8241 Axis to interpolate along. For `Series` this parameter is unused
8242 and defaults to 0.
8243 limit : int, optional
8244 Maximum number of consecutive NaNs to fill. In other words, if there
8245 is a gap with more than this number of consecutive NaNs, it will only
8246 be partially filled, from the direction given by ``limit_direction``.
8247 Must be greater than 0.
8248 inplace : bool, default False
8249 Update the data in place if possible.
8250 limit_direction : {'forward', 'backward', 'both'}, optional, default 'forward'
8251 Consecutive NaNs will be filled in this direction.
8253 limit_area : {`None`, 'inside', 'outside'}, default None
8254 Restrict which NaNs are filled based on their position relative to
8255 the valid values.
8257 * ``None``: No fill restriction.
8258 * 'inside': Only fill NaNs surrounded by valid values
8259 (interpolate).
8260 * 'outside': Only fill NaNs outside valid values (extrapolate).
8262 **kwargs : optional
8263 Keyword arguments to pass on to the interpolating function. Not
8264 all methods use them: the ``'linear'``, ``'time'``, ``'index'``,
8265 and ``'values'`` methods use NumPy and ignore any extra keyword
8266 arguments (for example, ``left`` and ``right``).
8268 Returns
8269 -------
8270 Series or DataFrame
8271 Returns the same object type as the caller, interpolated at
8272 some or all ``NaN`` values.
8274 See Also
8275 --------
8276 fillna : Fill missing values using different methods.
8277 scipy.interpolate.Akima1DInterpolator : Piecewise cubic polynomials
8278 (Akima interpolator).
8279 scipy.interpolate.BPoly.from_derivatives : Piecewise polynomial in the
8280 Bernstein basis.
8281 scipy.interpolate.interp1d : Interpolate a 1-D function.
8282 scipy.interpolate.KroghInterpolator : Interpolate polynomial (Krogh
8283 interpolator).
8284 scipy.interpolate.PchipInterpolator : PCHIP 1-d monotonic cubic
8285 interpolation.
8286 scipy.interpolate.CubicSpline : Cubic spline data interpolator.
8288 Notes
8289 -----
8290 The 'krogh', 'piecewise_polynomial', 'spline', 'pchip' and 'akima'
8291 methods are wrappers around the respective SciPy implementations of
8292 similar names. These use the actual numerical values of the index.
8293 For more information on their behavior, see the
8294 `SciPy documentation
8295 <https://docs.scipy.org/doc/scipy/reference/interpolate.html#univariate-interpolation>`__.
8297 Examples
8298 --------
8299 Filling in ``NaN`` in a :class:`~pandas.Series` via linear
8300 interpolation.
8302 >>> s = pd.Series([0, 1, np.nan, 3])
8303 >>> s
8304 0 0.0
8305 1 1.0
8306 2 NaN
8307 3 3.0
8308 dtype: float64
8309 >>> s.interpolate()
8310 0 0.0
8311 1 1.0
8312 2 2.0
8313 3 3.0
8314 dtype: float64
8316 Filling in ``NaN`` in a Series via polynomial interpolation or splines:
8317 Both 'polynomial' and 'spline' methods require that you also specify
8318 an ``order`` (int).
8320 >>> s = pd.Series([0, 2, np.nan, 8])
8321 >>> s.interpolate(method="polynomial", order=2)
8322 0 0.000000
8323 1 2.000000
8324 2 4.666667
8325 3 8.000000
8326 dtype: float64
8328 Fill the DataFrame forward (that is, going down) along each column
8329 using linear interpolation.
8331 Note how the last entry in column 'a' is interpolated differently,
8332 because there is no entry after it to use for interpolation.
8333 Note how the first entry in column 'b' remains ``NaN``, because there
8334 is no entry before it to use for interpolation.
8336 >>> df = pd.DataFrame(
8337 ... [
8338 ... (0.0, np.nan, -1.0, 1.0),
8339 ... (np.nan, 2.0, np.nan, np.nan),
8340 ... (2.0, 3.0, np.nan, 9.0),
8341 ... (np.nan, 4.0, -4.0, 16.0),
8342 ... ],
8343 ... columns=list("abcd"),
8344 ... )
8345 >>> df
8346 a b c d
8347 0 0.0 NaN -1.0 1.0
8348 1 NaN 2.0 NaN NaN
8349 2 2.0 3.0 NaN 9.0
8350 3 NaN 4.0 -4.0 16.0
8351 >>> df.interpolate(method="linear", limit_direction="forward", axis=0)
8352 a b c d
8353 0 0.0 NaN -1.0 1.0
8354 1 1.0 2.0 -2.0 5.0
8355 2 2.0 3.0 -3.0 9.0
8356 3 2.0 4.0 -4.0 16.0
8358 Using polynomial interpolation.
8360 >>> df["d"].interpolate(method="polynomial", order=2)
8361 0 1.0
8362 1 4.0
8363 2 9.0
8364 3 16.0
8365 Name: d, dtype: float64
8366 """
8367 inplace = validate_bool_kwarg(inplace, "inplace")
8369 if inplace:
8370 if not CHAINED_WARNING_DISABLED:
8371 if sys.getrefcount(
8372 self
8373 ) <= REF_COUNT_METHOD and not common.is_local_in_caller_frame(self):
8374 warnings.warn(
8375 _chained_assignment_method_msg,
8376 ChainedAssignmentError,
8377 stacklevel=2,
8378 )
8380 axis = self._get_axis_number(axis)
8382 if self.empty:
8383 return self if inplace else self.copy()
8385 if not isinstance(method, str):
8386 raise ValueError("'method' should be a string, not None.")
8388 obj, should_transpose = (self.T, True) if axis == 1 else (self, False)
8390 if isinstance(obj.index, MultiIndex) and method != "linear":
8391 raise ValueError(
8392 "Only `method=linear` interpolation is supported on MultiIndexes."
8393 )
8395 limit_direction = missing.infer_limit_direction(limit_direction, method)
8397 index = missing.get_interp_index(method, obj.index)
8398 new_data = obj._mgr.interpolate(
8399 method=method,
8400 index=index,
8401 limit=limit,
8402 limit_direction=limit_direction,
8403 limit_area=limit_area,
8404 inplace=inplace,
8405 **kwargs,
8406 )
8408 result = self._constructor_from_mgr(new_data, axes=new_data.axes)
8409 if should_transpose:
8410 result = result.T
8411 if inplace:
8412 self._update_inplace(result)
8413 return self
8414 else:
8415 return result.__finalize__(self, method="interpolate")
8417 # ----------------------------------------------------------------------
8418 # Timeseries methods Methods
8420 @final
8421 def asof(self, where, subset=None):
8422 """
8423 Return the last row(s) without any NaNs before `where`.
8425 The last row (for each element in `where`, if list) without any
8426 NaN is taken.
8427 In case of a :class:`~pandas.DataFrame`, the last row without NaN
8428 considering only the subset of columns (if not `None`)
8430 If there is no good value, NaN is returned for a Series or
8431 a Series of NaN values for a DataFrame
8433 Parameters
8434 ----------
8435 where : date or array-like of dates
8436 Date(s) before which the last row(s) are returned.
8437 subset : str or array-like of str, default `None`
8438 For DataFrame, if not `None`, only use these columns to
8439 check for NaNs.
8441 Returns
8442 -------
8443 scalar, Series, or DataFrame
8445 The return can be:
8447 * scalar : when `self` is a Series and `where` is a scalar
8448 * Series: when `self` is a Series and `where` is an array-like,
8449 or when `self` is a DataFrame and `where` is a scalar
8450 * DataFrame : when `self` is a DataFrame and `where` is an
8451 array-like
8453 See Also
8454 --------
8455 merge_asof : Perform an asof merge. Similar to left join.
8457 Notes
8458 -----
8459 Dates are assumed to be sorted. Raises if this is not the case.
8461 Examples
8462 --------
8463 A Series and a scalar `where`.
8465 >>> s = pd.Series([1, 2, np.nan, 4], index=[10, 20, 30, 40])
8466 >>> s
8467 10 1.0
8468 20 2.0
8469 30 NaN
8470 40 4.0
8471 dtype: float64
8473 >>> s.asof(20)
8474 np.float64(2.0)
8476 For a sequence `where`, a Series is returned. The first value is
8477 NaN, because the first element of `where` is before the first
8478 index value.
8480 >>> s.asof([5, 20])
8481 5 NaN
8482 20 2.0
8483 dtype: float64
8485 Missing values are not considered. The following is ``2.0``, not
8486 NaN, even though NaN is at the index location for ``30``.
8488 >>> s.asof(30)
8489 np.float64(2.0)
8491 Take all columns into consideration
8493 >>> df = pd.DataFrame(
8494 ... {
8495 ... "a": [10.0, 20.0, 30.0, 40.0, 50.0],
8496 ... "b": [None, None, None, None, 500],
8497 ... },
8498 ... index=pd.DatetimeIndex(
8499 ... [
8500 ... "2018-02-27 09:01:00",
8501 ... "2018-02-27 09:02:00",
8502 ... "2018-02-27 09:03:00",
8503 ... "2018-02-27 09:04:00",
8504 ... "2018-02-27 09:05:00",
8505 ... ]
8506 ... ),
8507 ... )
8508 >>> df.asof(pd.DatetimeIndex(["2018-02-27 09:03:30", "2018-02-27 09:04:30"]))
8509 a b
8510 2018-02-27 09:03:30 NaN NaN
8511 2018-02-27 09:04:30 NaN NaN
8513 Take a single column into consideration
8515 >>> df.asof(
8516 ... pd.DatetimeIndex(["2018-02-27 09:03:30", "2018-02-27 09:04:30"]),
8517 ... subset=["a"],
8518 ... )
8519 a b
8520 2018-02-27 09:03:30 30.0 NaN
8521 2018-02-27 09:04:30 40.0 NaN
8522 """
8523 if isinstance(where, str):
8524 where = Timestamp(where)
8526 if not self.index.is_monotonic_increasing:
8527 raise ValueError("asof requires a sorted index")
8529 is_series = isinstance(self, ABCSeries)
8530 if is_series:
8531 if subset is not None:
8532 raise ValueError("subset is not valid for Series")
8533 else:
8534 if subset is None:
8535 subset = self.columns
8536 if not is_list_like(subset):
8537 subset = [subset]
8539 is_list = is_list_like(where)
8540 if not is_list:
8541 start = self.index[0]
8542 if isinstance(self.index, PeriodIndex):
8543 where = Period(where, freq=self.index.freq)
8545 if where < start:
8546 if not is_series:
8547 return self._constructor_sliced(
8548 index=self.columns, name=where, dtype=np.float64
8549 )
8550 return np.nan
8552 # It's always much faster to use a *while* loop here for
8553 # Series than pre-computing all the NAs. However a
8554 # *while* loop is extremely expensive for DataFrame
8555 # so we later pre-compute all the NAs and use the same
8556 # code path whether *where* is a scalar or list.
8557 # See PR: https://github.com/pandas-dev/pandas/pull/14476
8558 if is_series:
8559 loc = self.index.searchsorted(where, side="right")
8560 if loc > 0:
8561 loc -= 1
8563 values = self._values
8564 while loc > 0 and isna(values[loc]):
8565 loc -= 1
8566 return values[loc]
8568 if not isinstance(where, Index):
8569 where = Index(where) if is_list else Index([where])
8571 nulls = self.isna() if is_series else self[subset].isna().any(axis=1)
8572 if nulls.all():
8573 if is_series:
8574 self = cast("Series", self)
8575 return self._constructor(np.nan, index=where, name=self.name)
8576 elif is_list:
8577 self = cast("DataFrame", self)
8578 return self._constructor(np.nan, index=where, columns=self.columns)
8579 else:
8580 self = cast("DataFrame", self)
8581 return self._constructor_sliced(
8582 np.nan, index=self.columns, name=where[0]
8583 )
8585 # error: Unsupported operand type for
8586 # ~ ("ExtensionArray | ndarray[Any, Any] | Any")
8587 locs = self.index.asof_locs(where, ~nulls._values) # type: ignore[operator]
8589 # mask the missing
8590 mask = locs == -1
8591 data = self.take(locs)
8592 data.index = where
8593 if mask.any():
8594 # GH#16063 only do this setting when necessary, otherwise
8595 # we'd cast e.g. bools to floats
8596 data.loc[mask] = np.nan
8597 return data if is_list else data.iloc[-1]
8599 # ----------------------------------------------------------------------
8600 # Action Methods
8602 def isna(self) -> Self:
8603 """
8604 Detect missing values.
8606 Return a boolean same-sized object indicating if the values are NA.
8607 NA values, such as None or :attr:`numpy.NaN`, gets mapped to True
8608 values.
8609 Everything else gets mapped to False values. Characters such as empty
8610 strings ``''`` or :attr:`numpy.inf` are not considered NA values.
8612 Returns
8613 -------
8614 Series/DataFrame
8615 Mask of bool values for each element in Series/DataFrame
8616 that indicates whether an element is an NA value.
8618 See Also
8619 --------
8620 Series.isnull : Alias of isna.
8621 DataFrame.isnull : Alias of isna.
8622 Series.notna : Boolean inverse of isna.
8623 DataFrame.notna : Boolean inverse of isna.
8624 Series.dropna : Omit axes labels with missing values.
8625 DataFrame.dropna : Omit axes labels with missing values.
8626 isna : Top-level isna.
8628 Examples
8629 --------
8630 Show which entries in a DataFrame are NA.
8632 >>> df = pd.DataFrame(
8633 ... dict(
8634 ... age=[5, 6, np.nan],
8635 ... born=[
8636 ... pd.NaT,
8637 ... pd.Timestamp("1939-05-27"),
8638 ... pd.Timestamp("1940-04-25"),
8639 ... ],
8640 ... name=["Alfred", "Batman", ""],
8641 ... toy=[None, "Batmobile", "Joker"],
8642 ... )
8643 ... )
8644 >>> df
8645 age born name toy
8646 0 5.0 NaT Alfred NaN
8647 1 6.0 1939-05-27 Batman Batmobile
8648 2 NaN 1940-04-25 Joker
8650 >>> df.isna()
8651 age born name toy
8652 0 False True False True
8653 1 False False False False
8654 2 True False False False
8656 Show which entries in a Series are NA.
8658 >>> ser = pd.Series([5, 6, np.nan])
8659 >>> ser
8660 0 5.0
8661 1 6.0
8662 2 NaN
8663 dtype: float64
8665 >>> ser.isna()
8666 0 False
8667 1 False
8668 2 True
8669 dtype: bool
8670 """
8671 return isna(self).__finalize__(self, method="isna")
8673 def isnull(self) -> Self:
8674 """
8675 Detect missing values.
8677 Return a boolean same-sized object indicating if the values are NA.
8678 NA values, such as None or :attr:`numpy.NaN`, gets mapped to True
8679 values.
8680 Everything else gets mapped to False values. Characters such as empty
8681 strings ``''`` or :attr:`numpy.inf` are not considered NA values.
8683 Returns
8684 -------
8685 Series/DataFrame
8686 Mask of bool values for each element in Series/DataFrame
8687 that indicates whether an element is an NA value.
8689 See Also
8690 --------
8691 Series.isna : Alias of isnull.
8692 DataFrame.isna : Alias of isnull.
8693 Series.notna : Boolean inverse of isnull.
8694 DataFrame.notna : Boolean inverse of isnull.
8695 Series.dropna : Omit axes labels with missing values.
8696 DataFrame.dropna : Omit axes labels with missing values.
8697 isna : Top-level isna.
8699 Examples
8700 --------
8701 Show which entries in a DataFrame are NA.
8703 >>> df = pd.DataFrame(
8704 ... dict(
8705 ... age=[5, 6, np.nan],
8706 ... born=[
8707 ... pd.NaT,
8708 ... pd.Timestamp("1939-05-27"),
8709 ... pd.Timestamp("1940-04-25"),
8710 ... ],
8711 ... name=["Alfred", "Batman", ""],
8712 ... toy=[None, "Batmobile", "Joker"],
8713 ... )
8714 ... )
8715 >>> df
8716 age born name toy
8717 0 5.0 NaT Alfred NaN
8718 1 6.0 1939-05-27 Batman Batmobile
8719 2 NaN 1940-04-25 Joker
8721 >>> df.isna()
8722 age born name toy
8723 0 False True False True
8724 1 False False False False
8725 2 True False False False
8727 Show which entries in a Series are NA.
8729 >>> ser = pd.Series([5, 6, np.nan])
8730 >>> ser
8731 0 5.0
8732 1 6.0
8733 2 NaN
8734 dtype: float64
8736 >>> ser.isna()
8737 0 False
8738 1 False
8739 2 True
8740 dtype: bool
8741 """
8742 return isna(self).__finalize__(self, method="isnull")
8744 def notna(self) -> Self:
8745 """
8746 Detect existing (non-missing) values.
8748 Return a boolean same-sized object indicating if the values are not NA.
8749 Non-missing values get mapped to True. Characters such as empty
8750 strings ``''`` or :attr:`numpy.inf` are not considered NA values.
8751 NA values, such as None or :attr:`numpy.NaN`, get mapped to False
8752 values.
8754 Returns
8755 -------
8756 Series/DataFrame
8757 Mask of bool values for each element in Series/DataFrame
8758 that indicates whether an element is not an NA value.
8760 See Also
8761 --------
8762 Series.notnull : Alias of notna.
8763 DataFrame.notnull : Alias of notna.
8764 Series.isna : Boolean inverse of notna.
8765 DataFrame.isna : Boolean inverse of notna.
8766 Series.dropna : Omit axes labels with missing values.
8767 DataFrame.dropna : Omit axes labels with missing values.
8768 notna : Top-level notna.
8770 Examples
8771 --------
8772 Show which entries in a DataFrame are not NA.
8774 >>> df = pd.DataFrame(
8775 ... dict(
8776 ... age=[5, 6, np.nan],
8777 ... born=[
8778 ... pd.NaT,
8779 ... pd.Timestamp("1939-05-27"),
8780 ... pd.Timestamp("1940-04-25"),
8781 ... ],
8782 ... name=["Alfred", "Batman", ""],
8783 ... toy=[None, "Batmobile", "Joker"],
8784 ... )
8785 ... )
8786 >>> df
8787 age born name toy
8788 0 5.0 NaT Alfred NaN
8789 1 6.0 1939-05-27 Batman Batmobile
8790 2 NaN 1940-04-25 Joker
8792 >>> df.notna()
8793 age born name toy
8794 0 True False True False
8795 1 True True True True
8796 2 False True True True
8798 Show which entries in a Series are not NA.
8800 >>> ser = pd.Series([5, 6, np.nan])
8801 >>> ser
8802 0 5.0
8803 1 6.0
8804 2 NaN
8805 dtype: float64
8807 >>> ser.notna()
8808 0 True
8809 1 True
8810 2 False
8811 dtype: bool
8812 """
8813 return notna(self).__finalize__(self, method="notna")
8815 def notnull(self) -> Self:
8816 """
8817 Detect existing (non-missing) values.
8819 Return a boolean same-sized object indicating if the values are not NA.
8820 Non-missing values get mapped to True. Characters such as empty
8821 strings ``''`` or :attr:`numpy.inf` are not considered NA values.
8822 NA values, such as None or :attr:`numpy.NaN`, get mapped to False
8823 values.
8825 Returns
8826 -------
8827 Series/DataFrame
8828 Mask of bool values for each element in Series/DataFrame
8829 that indicates whether an element is not an NA value.
8831 See Also
8832 --------
8833 Series.notnull : Alias of notna.
8834 DataFrame.notnull : Alias of notna.
8835 Series.isna : Boolean inverse of notna.
8836 DataFrame.isna : Boolean inverse of notna.
8837 Series.dropna : Omit axes labels with missing values.
8838 DataFrame.dropna : Omit axes labels with missing values.
8839 notna : Top-level notna.
8841 Examples
8842 --------
8843 Show which entries in a DataFrame are not NA.
8845 >>> df = pd.DataFrame(
8846 ... dict(
8847 ... age=[5, 6, np.nan],
8848 ... born=[
8849 ... pd.NaT,
8850 ... pd.Timestamp("1939-05-27"),
8851 ... pd.Timestamp("1940-04-25"),
8852 ... ],
8853 ... name=["Alfred", "Batman", ""],
8854 ... toy=[None, "Batmobile", "Joker"],
8855 ... )
8856 ... )
8857 >>> df
8858 age born name toy
8859 0 5.0 NaT Alfred NaN
8860 1 6.0 1939-05-27 Batman Batmobile
8861 2 NaN 1940-04-25 Joker
8863 >>> df.notna()
8864 age born name toy
8865 0 True False True False
8866 1 True True True True
8867 2 False True True True
8869 Show which entries in a Series are not NA.
8871 >>> ser = pd.Series([5, 6, np.nan])
8872 >>> ser
8873 0 5.0
8874 1 6.0
8875 2 NaN
8876 dtype: float64
8878 >>> ser.notna()
8879 0 True
8880 1 True
8881 2 False
8882 dtype: bool
8883 """
8884 return notna(self).__finalize__(self, method="notnull")
8886 @final
8887 def _clip_with_scalar(self, lower, upper, inplace: bool = False):
8888 if (lower is not None and np.any(isna(lower))) or (
8889 upper is not None and np.any(isna(upper))
8890 ):
8891 raise ValueError("Cannot use an NA value as a clip threshold")
8893 result = self
8894 mask = self.isna()
8896 if lower is not None:
8897 cond = mask | (self >= lower)
8898 result = result.where(cond, lower, inplace=inplace)
8899 if upper is not None:
8900 cond = mask | (self <= upper)
8901 result = result.where(cond, upper, inplace=inplace)
8903 return result
8905 @final
8906 def _clip_with_one_bound(self, threshold, method, axis, inplace):
8907 if axis is not None:
8908 axis = self._get_axis_number(axis)
8910 # method is self.le for upper bound and self.ge for lower bound
8911 if is_scalar(threshold) and is_number(threshold):
8912 if method.__name__ == "le":
8913 return self._clip_with_scalar(None, threshold, inplace=inplace)
8914 return self._clip_with_scalar(threshold, None, inplace=inplace)
8916 # GH #15390
8917 # In order for where method to work, the threshold must
8918 # be transformed to NDFrame from other array like structure.
8919 if (not isinstance(threshold, ABCSeries)) and is_list_like(threshold):
8920 if isinstance(self, ABCSeries):
8921 threshold = self._constructor(threshold, index=self.index)
8922 else:
8923 threshold = self._align_for_op(threshold, axis, flex=None)[1]
8924 if axis is None and isinstance(threshold, ABCSeries):
8925 # _align_for_op aligned the 1D bound on self.columns;
8926 # `where` below needs that spelled out (GH#68929)
8927 axis = 1
8929 # GH 40420
8930 # Treat missing thresholds as no bounds, not clipping the values
8931 if is_list_like(threshold):
8932 fill_value = np.inf if method.__name__ == "le" else -np.inf
8933 threshold_inf = threshold.fillna(fill_value)
8934 else:
8935 threshold_inf = threshold
8937 subset = method(threshold_inf, axis=axis) | isna(self)
8939 # GH 40420
8940 return self.where(subset, threshold, axis=axis, inplace=inplace)
8942 @final
8943 def clip(
8944 self,
8945 lower=None,
8946 upper=None,
8947 *,
8948 axis: Axis | None = None,
8949 inplace: bool = False,
8950 **kwargs,
8951 ) -> Self:
8952 """
8953 Trim values at input threshold(s).
8955 Assigns values outside boundary to boundary values. Thresholds
8956 can be singular values or array like, and in the latter case
8957 the clipping is performed element-wise in the specified axis.
8959 Parameters
8960 ----------
8961 lower : float or array-like, default None
8962 Minimum threshold value. All values below this
8963 threshold will be set to it. A missing
8964 threshold (e.g `NA`) will not clip the value.
8965 upper : float or array-like, default None
8966 Maximum threshold value. All values above this
8967 threshold will be set to it. A missing
8968 threshold (e.g `NA`) will not clip the value.
8969 axis : {0 or 'index', 1 or 'columns', None}, default None
8970 Align object with lower and upper along the given axis.
8971 For `Series` this parameter is unused and defaults to `None`.
8972 inplace : bool, default False
8973 Whether to perform the operation in place on the data.
8974 **kwargs
8975 For compatibility with NumPy. See :ref:`gotchas.numpy_kwargs` for more.
8977 Returns
8978 -------
8979 Series or DataFrame
8980 Same type as calling object with the values outside the
8981 clip boundaries replaced.
8983 See Also
8984 --------
8985 Series.clip : Trim values at input threshold in series.
8986 DataFrame.clip : Trim values at input threshold in DataFrame.
8987 numpy.clip : Clip (limit) the values in an array.
8989 Examples
8990 --------
8991 >>> data = {"col_0": [9, -3, 0, -1, 5], "col_1": [-2, -7, 6, 8, -5]}
8992 >>> df = pd.DataFrame(data)
8993 >>> df
8994 col_0 col_1
8995 0 9 -2
8996 1 -3 -7
8997 2 0 6
8998 3 -1 8
8999 4 5 -5
9001 Clips per column using lower and upper thresholds:
9003 >>> df.clip(-4, 6)
9004 col_0 col_1
9005 0 6 -2
9006 1 -3 -4
9007 2 0 6
9008 3 -1 6
9009 4 5 -4
9011 Clips using specific lower and upper thresholds per column:
9013 >>> df.clip([-2, -1], [4, 5])
9014 col_0 col_1
9015 0 4 -1
9016 1 -2 -1
9017 2 0 5
9018 3 -1 5
9019 4 4 -1
9021 Clips using specific lower and upper thresholds per column element:
9023 >>> t = pd.Series([2, -4, -1, 6, 3])
9024 >>> t
9025 0 2
9026 1 -4
9027 2 -1
9028 3 6
9029 4 3
9030 dtype: int64
9032 >>> df.clip(t, t + 4, axis=0)
9033 col_0 col_1
9034 0 6 2
9035 1 -3 -4
9036 2 0 3
9037 3 6 8
9038 4 5 3
9040 Clips using specific lower threshold per column element, with missing values:
9042 >>> t = pd.Series([2, -4, np.nan, 6, 3])
9043 >>> t
9044 0 2.0
9045 1 -4.0
9046 2 NaN
9047 3 6.0
9048 4 3.0
9049 dtype: float64
9051 >>> df.clip(t, axis=0)
9052 col_0 col_1
9053 0 9.0 2.0
9054 1 -3.0 -4.0
9055 2 0.0 6.0
9056 3 6.0 8.0
9057 4 5.0 3.0
9058 """
9059 inplace = validate_bool_kwarg(inplace, "inplace")
9061 if inplace:
9062 if not CHAINED_WARNING_DISABLED:
9063 if sys.getrefcount(
9064 self
9065 ) <= REF_COUNT_METHOD and not common.is_local_in_caller_frame(self):
9066 warnings.warn(
9067 _chained_assignment_method_msg,
9068 ChainedAssignmentError,
9069 stacklevel=2,
9070 )
9072 axis = nv.validate_clip_with_axis(axis, (), kwargs)
9073 if axis is not None:
9074 axis = self._get_axis_number(axis)
9076 # GH 17276
9077 # numpy doesn't like NaN as a clip value
9078 # so ignore
9079 # GH 19992
9080 # numpy doesn't drop a list-like bound containing NaN
9081 isna_lower = isna(lower)
9082 if not is_list_like(lower):
9083 if np.any(isna_lower):
9084 lower = None
9085 elif np.all(isna_lower):
9086 lower = None
9087 isna_upper = isna(upper)
9088 if not is_list_like(upper):
9089 if np.any(isna_upper):
9090 upper = None
9091 elif np.all(isna_upper):
9092 upper = None
9094 # GH 2747 (arguments were reversed)
9095 if (
9096 lower is not None
9097 and upper is not None
9098 and is_scalar(lower)
9099 and is_scalar(upper)
9100 ):
9101 lower, upper = min(lower, upper), max(lower, upper)
9103 # fast-path for scalars
9104 if (lower is None or is_number(lower)) and (upper is None or is_number(upper)):
9105 return self._clip_with_scalar(lower, upper, inplace=inplace)
9107 result = self
9108 if lower is not None:
9109 result = result._clip_with_one_bound(
9110 lower, method=self.ge, axis=axis, inplace=inplace
9111 )
9112 if upper is not None:
9113 if inplace:
9114 result = self
9115 result = result._clip_with_one_bound(
9116 upper, method=self.le, axis=axis, inplace=inplace
9117 )
9119 return result
9121 @final
9122 def asfreq(
9123 self,
9124 freq: Frequency,
9125 method: FillnaOptions | None = None,
9126 how: ToTimestampHow | None = None,
9127 normalize: bool = False,
9128 fill_value: Hashable | None = None,
9129 ) -> Self:
9130 """
9131 Convert time series to specified frequency.
9133 Returns the original data conformed to a new index with the specified
9134 frequency.
9136 If the index of this Series/DataFrame is a :class:`~pandas.PeriodIndex`, the
9137 new index is the result of transforming the original index with
9138 :meth:`PeriodIndex.asfreq <pandas.PeriodIndex.asfreq>` (so the original index
9139 will map one-to-one to the new index).
9141 Otherwise, the new index will be equivalent to ``pd.date_range(start, end,
9142 freq=freq)`` where ``start`` and ``end`` are, respectively, the min and
9143 max entries in the original index (see :func:`pandas.date_range`). The
9144 values corresponding to any timesteps in the new index which were not present
9145 in the original index will be null (``NaN``), unless a method for filling
9146 such unknowns is provided (see the ``method`` parameter below).
9148 The :meth:`resample` method is more appropriate if an operation on each group of
9149 timesteps (such as an aggregate) is necessary to represent the data at the new
9150 frequency.
9152 Parameters
9153 ----------
9154 freq : DateOffset or str
9155 Frequency DateOffset or string.
9156 method : {'backfill'/'bfill', 'pad'/'ffill'}, default None
9157 Method to use for filling holes in reindexed Series (note this
9158 does not fill NaNs that already were present):
9160 * 'pad' / 'ffill': propagate last valid observation forward to next
9161 valid based on the order of the index
9162 * 'backfill' / 'bfill': use NEXT valid observation to fill.
9163 how : {'end', 'start', 'e', 's'}, default 'end'
9164 For PeriodIndex only (see PeriodIndex.asfreq).
9165 normalize : bool, default False
9166 Whether to reset output index to midnight.
9167 fill_value : scalar, optional
9168 Value to use for missing values, applied during upsampling (note
9169 this does not fill NaNs that already were present).
9171 Returns
9172 -------
9173 Series/DataFrame
9174 Series/DataFrame object reindexed to the specified frequency.
9176 See Also
9177 --------
9178 reindex : Conform DataFrame to new index with optional filling logic.
9180 Notes
9181 -----
9182 To learn more about the frequency strings, please see
9183 :ref:`this link<timeseries.offset_aliases>`.
9185 Examples
9186 --------
9187 Start by creating a series with 4 one minute timestamps.
9189 >>> index = pd.date_range("1/1/2000", periods=4, freq="min")
9190 >>> series = pd.Series([0.0, None, 2.0, 3.0], index=index)
9191 >>> df = pd.DataFrame({"s": series})
9192 >>> df
9193 s
9194 2000-01-01 00:00:00 0.0
9195 2000-01-01 00:01:00 NaN
9196 2000-01-01 00:02:00 2.0
9197 2000-01-01 00:03:00 3.0
9199 Upsample the series into 30 second bins.
9201 >>> df.asfreq(freq="30s")
9202 s
9203 2000-01-01 00:00:00 0.0
9204 2000-01-01 00:00:30 NaN
9205 2000-01-01 00:01:00 NaN
9206 2000-01-01 00:01:30 NaN
9207 2000-01-01 00:02:00 2.0
9208 2000-01-01 00:02:30 NaN
9209 2000-01-01 00:03:00 3.0
9211 Upsample again, providing a ``fill value``.
9213 >>> df.asfreq(freq="30s", fill_value=9.0)
9214 s
9215 2000-01-01 00:00:00 0.0
9216 2000-01-01 00:00:30 9.0
9217 2000-01-01 00:01:00 NaN
9218 2000-01-01 00:01:30 9.0
9219 2000-01-01 00:02:00 2.0
9220 2000-01-01 00:02:30 9.0
9221 2000-01-01 00:03:00 3.0
9223 Upsample again, providing a ``method``.
9225 >>> df.asfreq(freq="30s", method="bfill")
9226 s
9227 2000-01-01 00:00:00 0.0
9228 2000-01-01 00:00:30 NaN
9229 2000-01-01 00:01:00 NaN
9230 2000-01-01 00:01:30 2.0
9231 2000-01-01 00:02:00 2.0
9232 2000-01-01 00:02:30 3.0
9233 2000-01-01 00:03:00 3.0
9234 """
9235 from pandas.core.resample import asfreq
9237 return asfreq(
9238 self,
9239 freq,
9240 method=method,
9241 how=how,
9242 normalize=normalize,
9243 fill_value=fill_value,
9244 )
9246 @final
9247 def at_time(self, time, asof: bool = False, axis: Axis | None = None) -> Self:
9248 """
9249 Select values at particular time of day (e.g., 9:30AM).
9251 This method filters rows whose index has a time component matching
9252 the specified time. The index must be a DatetimeIndex.
9254 Parameters
9255 ----------
9256 time : datetime.time or str
9257 The values to select.
9258 asof : bool, default False
9259 This parameter is currently not supported.
9260 axis : {0 or 'index', 1 or 'columns'}, default 0
9261 For `Series` this parameter is unused and defaults to 0.
9263 Returns
9264 -------
9265 Series or DataFrame
9266 The values with the specified time.
9268 Raises
9269 ------
9270 TypeError
9271 If the index is not a :class:`DatetimeIndex`
9273 See Also
9274 --------
9275 between_time : Select values between particular times of the day.
9276 DatetimeIndex.indexer_at_time : Get just the index locations for
9277 values at particular time of the day.
9279 Examples
9280 --------
9281 >>> i = pd.date_range("2018-04-09", periods=4, freq="12h")
9282 >>> ts = pd.DataFrame({"A": [1, 2, 3, 4]}, index=i)
9283 >>> ts
9284 A
9285 2018-04-09 00:00:00 1
9286 2018-04-09 12:00:00 2
9287 2018-04-10 00:00:00 3
9288 2018-04-10 12:00:00 4
9290 >>> ts.at_time("12:00")
9291 A
9292 2018-04-09 12:00:00 2
9293 2018-04-10 12:00:00 4
9294 """
9295 if axis is None:
9296 axis = 0
9297 axis = self._get_axis_number(axis)
9299 index = self._get_axis(axis)
9301 if not isinstance(index, DatetimeIndex):
9302 raise TypeError("Index must be DatetimeIndex")
9304 indexer = index.indexer_at_time(time, asof=asof)
9305 return self.take(indexer, axis=axis)
9307 @final
9308 def between_time(
9309 self,
9310 start_time,
9311 end_time,
9312 inclusive: IntervalClosedType = "both",
9313 axis: Axis | None = None,
9314 ) -> Self:
9315 """
9316 Select values between particular times of the day (e.g., 9:00-9:30 AM).
9318 By setting ``start_time`` to be later than ``end_time``,
9319 you can get the times that are *not* between the two times.
9321 Parameters
9322 ----------
9323 start_time : datetime.time or str
9324 Initial time as a time filter limit.
9325 end_time : datetime.time or str
9326 End time as a time filter limit.
9327 inclusive : {"both", "neither", "left", "right"}, default "both"
9328 Include boundaries; whether to set each bound as closed or open.
9329 axis : {0 or 'index', 1 or 'columns'}, default 0
9330 Determine range time on index or columns value.
9331 For `Series` this parameter is unused and defaults to 0.
9333 Returns
9334 -------
9335 Series or DataFrame
9336 Data from the original object filtered to the specified dates range.
9338 Raises
9339 ------
9340 TypeError
9341 If the index is not a :class:`DatetimeIndex`
9343 See Also
9344 --------
9345 at_time : Select values at a particular time of the day.
9346 DatetimeIndex.indexer_between_time : Get just the index locations for
9347 values between particular times of the day.
9349 Examples
9350 --------
9351 >>> i = pd.date_range("2018-04-09", periods=4, freq="1D20min")
9352 >>> ts = pd.DataFrame({"A": [1, 2, 3, 4]}, index=i)
9353 >>> ts
9354 A
9355 2018-04-09 00:00:00 1
9356 2018-04-10 00:20:00 2
9357 2018-04-11 00:40:00 3
9358 2018-04-12 01:00:00 4
9360 >>> ts.between_time("0:15", "0:45")
9361 A
9362 2018-04-10 00:20:00 2
9363 2018-04-11 00:40:00 3
9365 You get the times that are *not* between two times by setting
9366 ``start_time`` later than ``end_time``:
9368 >>> ts.between_time("0:45", "0:15")
9369 A
9370 2018-04-09 00:00:00 1
9371 2018-04-12 01:00:00 4
9372 """
9373 if axis is None:
9374 axis = 0
9375 axis = self._get_axis_number(axis)
9377 index = self._get_axis(axis)
9378 if not isinstance(index, DatetimeIndex):
9379 raise TypeError("Index must be DatetimeIndex")
9381 left_inclusive, right_inclusive = validate_inclusive(inclusive)
9382 indexer = index.indexer_between_time(
9383 start_time,
9384 end_time,
9385 include_start=left_inclusive,
9386 include_end=right_inclusive,
9387 )
9388 return self.take(indexer, axis=axis)
9390 @final
9391 def resample(
9392 self,
9393 rule,
9394 closed: Literal["right", "left"] | None = None,
9395 label: Literal["right", "left"] | None = None,
9396 convention: Literal["start", "end", "s", "e"] = "start",
9397 on: Level | None = None,
9398 level: Level | None = None,
9399 origin: str | TimestampConvertibleTypes = "start_day",
9400 offset: TimedeltaConvertibleTypes | None = None,
9401 group_keys: bool = False,
9402 ) -> Resampler:
9403 """
9404 Resample time-series data.
9406 Convenience method for frequency conversion and resampling of time series.
9407 The object must have a datetime-like index (`DatetimeIndex`, `PeriodIndex`,
9408 or `TimedeltaIndex`), or the caller must pass the label of a datetime-like
9409 series/index to the ``on``/``level`` keyword parameter.
9411 Parameters
9412 ----------
9413 rule : DateOffset, Timedelta or str
9414 The offset string or object representing target conversion.
9415 closed : {'right', 'left'}, default None
9416 Which side of bin interval is closed. The default is 'left'
9417 for all frequency offsets except for 'ME', 'YE', 'QE', 'BME',
9418 'BA', 'BQE', and 'W' which all have a default of 'right'.
9419 label : {'right', 'left'}, default None
9420 Which bin edge label to label bucket with. The default is 'left'
9421 for all frequency offsets except for 'ME', 'YE', 'QE', 'BME',
9422 'BA', 'BQE', and 'W' which all have a default of 'right'.
9423 convention : {'start', 'end', 's', 'e'}, default 'start'
9424 For `PeriodIndex` only, controls whether to use the start or
9425 end of `rule`.
9426 on : str, optional
9427 For a DataFrame, column to use instead of index for resampling.
9428 Column must be datetime-like.
9429 level : str or int, optional
9430 For a MultiIndex, level (name or number) to use for
9431 resampling. `level` must be datetime-like.
9432 origin : Timestamp or str, default 'start_day'
9433 The timestamp on which to adjust the grouping. The timezone of origin
9434 must match the timezone of the index.
9435 If string, must be Timestamp convertible or one of the following:
9437 - 'epoch': `origin` is 1970-01-01
9438 - 'start': `origin` is the first value of the timeseries
9439 - 'start_day': `origin` is the first day at midnight of the timeseries
9441 - 'end': `origin` is the last value of the timeseries
9442 - 'end_day': `origin` is the ceiling midnight of the last day
9444 .. note::
9446 Only takes effect for Tick-frequencies (i.e. fixed frequencies
9447 like hours and minutes) and, on a timezone-naive index, for day
9448 frequencies; not for months or quarters.
9449 offset : Timedelta or str, default is None
9450 An offset timedelta added to the origin.
9452 group_keys : bool, default False
9453 Whether to include the group keys in the result index when using
9454 ``.apply()`` on the resampled object.
9456 .. versionchanged:: 2.0.0
9458 ``group_keys`` now defaults to ``False``.
9460 Returns
9461 -------
9462 pandas.api.typing.Resampler
9463 :class:`~pandas.core.Resampler` object.
9465 See Also
9466 --------
9467 Series.resample : Resample a Series.
9468 DataFrame.resample : Resample a DataFrame.
9469 groupby : Group Series/DataFrame by mapping, function, label, or list of labels.
9470 asfreq : Reindex a Series/DataFrame with the given frequency without grouping.
9472 Notes
9473 -----
9474 See the `user guide
9475 <https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#resampling>`__
9476 for more.
9478 To learn more about the offset strings, please see `this link
9479 <https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#dateoffset-objects>`__.
9481 Examples
9482 --------
9483 Start by creating a series with 9 one minute timestamps.
9485 >>> index = pd.date_range("1/1/2000", periods=9, freq="min")
9486 >>> series = pd.Series(range(9), index=index)
9487 >>> series
9488 2000-01-01 00:00:00 0
9489 2000-01-01 00:01:00 1
9490 2000-01-01 00:02:00 2
9491 2000-01-01 00:03:00 3
9492 2000-01-01 00:04:00 4
9493 2000-01-01 00:05:00 5
9494 2000-01-01 00:06:00 6
9495 2000-01-01 00:07:00 7
9496 2000-01-01 00:08:00 8
9497 Freq: min, dtype: int64
9499 Downsample the series into 3 minute bins and sum the values
9500 of the timestamps falling into a bin.
9502 >>> series.resample("3min").sum()
9503 2000-01-01 00:00:00 3
9504 2000-01-01 00:03:00 12
9505 2000-01-01 00:06:00 21
9506 Freq: 3min, dtype: int64
9508 Downsample the series into 3 minute bins as above, but label each
9509 bin using the right edge instead of the left. Please note that the
9510 value in the bucket used as the label is not included in the bucket,
9511 which it labels. For example, in the original series the
9512 bucket ``2000-01-01 00:03:00`` contains the value 3, but the summed
9513 value in the resampled bucket with the label ``2000-01-01 00:03:00``
9514 does not include 3 (if it did, the summed value would be 6, not 3).
9516 >>> series.resample("3min", label="right").sum()
9517 2000-01-01 00:03:00 3
9518 2000-01-01 00:06:00 12
9519 2000-01-01 00:09:00 21
9520 Freq: 3min, dtype: int64
9522 To include this value close the right side of the bin interval,
9523 as shown below.
9525 >>> series.resample("3min", label="right", closed="right").sum()
9526 2000-01-01 00:00:00 0
9527 2000-01-01 00:03:00 6
9528 2000-01-01 00:06:00 15
9529 2000-01-01 00:09:00 15
9530 Freq: 3min, dtype: int64
9532 Upsample the series into 30 second bins.
9534 >>> series.resample("30s").asfreq()[0:5] # Select first 5 rows
9535 2000-01-01 00:00:00 0.0
9536 2000-01-01 00:00:30 NaN
9537 2000-01-01 00:01:00 1.0
9538 2000-01-01 00:01:30 NaN
9539 2000-01-01 00:02:00 2.0
9540 Freq: 30s, dtype: float64
9542 Upsample the series into 30 second bins and fill the ``NaN``
9543 values using the ``ffill`` method.
9545 >>> series.resample("30s").ffill()[0:5]
9546 2000-01-01 00:00:00 0
9547 2000-01-01 00:00:30 0
9548 2000-01-01 00:01:00 1
9549 2000-01-01 00:01:30 1
9550 2000-01-01 00:02:00 2
9551 Freq: 30s, dtype: int64
9553 Upsample the series into 30 second bins and fill the
9554 ``NaN`` values using the ``bfill`` method.
9556 >>> series.resample("30s").bfill()[0:5]
9557 2000-01-01 00:00:00 0
9558 2000-01-01 00:00:30 1
9559 2000-01-01 00:01:00 1
9560 2000-01-01 00:01:30 2
9561 2000-01-01 00:02:00 2
9562 Freq: 30s, dtype: int64
9564 Pass a custom function via ``apply``
9566 >>> def custom_resampler(arraylike):
9567 ... return np.sum(arraylike) + 5
9568 >>> series.resample("3min").apply(custom_resampler)
9569 2000-01-01 00:00:00 8
9570 2000-01-01 00:03:00 17
9571 2000-01-01 00:06:00 26
9572 Freq: 3min, dtype: int64
9574 For a Series with a PeriodIndex, the keyword `convention` can be
9575 used to control whether to use the start or end of `rule`.
9577 Resample a year by quarter using 'start' `convention`. Values are
9578 assigned to the first quarter of the period.
9580 >>> s = pd.Series(
9581 ... [1, 2], index=pd.period_range("2012-01-01", freq="Y", periods=2)
9582 ... )
9583 >>> s
9584 2012 1
9585 2013 2
9586 Freq: Y-DEC, dtype: int64
9587 >>> s.resample("Q", convention="start").asfreq()
9588 2012Q1 1.0
9589 2012Q2 NaN
9590 2012Q3 NaN
9591 2012Q4 NaN
9592 2013Q1 2.0
9593 2013Q2 NaN
9594 2013Q3 NaN
9595 2013Q4 NaN
9596 Freq: Q-DEC, dtype: float64
9598 Resample quarters by month using 'end' `convention`. Values are
9599 assigned to the last month of the period.
9601 >>> q = pd.Series(
9602 ... [1, 2, 3, 4], index=pd.period_range("2018-01-01", freq="Q", periods=4)
9603 ... )
9604 >>> q
9605 2018Q1 1
9606 2018Q2 2
9607 2018Q3 3
9608 2018Q4 4
9609 Freq: Q-DEC, dtype: int64
9610 >>> q.resample("M", convention="end").asfreq()
9611 2018-03 1.0
9612 2018-04 NaN
9613 2018-05 NaN
9614 2018-06 2.0
9615 2018-07 NaN
9616 2018-08 NaN
9617 2018-09 3.0
9618 2018-10 NaN
9619 2018-11 NaN
9620 2018-12 4.0
9621 Freq: M, dtype: float64
9623 For DataFrame objects, the keyword `on` can be used to specify the
9624 column instead of the index for resampling.
9626 >>> df = pd.DataFrame([10, 11, 9, 13, 14, 18, 17, 19], columns=["price"])
9627 >>> df["volume"] = [50, 60, 40, 100, 50, 100, 40, 50]
9628 >>> df["week_starting"] = pd.date_range("01/01/2018", periods=8, freq="W")
9629 >>> df
9630 price volume week_starting
9631 0 10 50 2018-01-07
9632 1 11 60 2018-01-14
9633 2 9 40 2018-01-21
9634 3 13 100 2018-01-28
9635 4 14 50 2018-02-04
9636 5 18 100 2018-02-11
9637 6 17 40 2018-02-18
9638 7 19 50 2018-02-25
9639 >>> df.resample("ME", on="week_starting").mean()
9640 price volume
9641 week_starting
9642 2018-01-31 10.75 62.5
9643 2018-02-28 17.00 60.0
9645 For a DataFrame with MultiIndex, the keyword `level` can be used to
9646 specify on which level the resampling needs to take place.
9648 >>> days = pd.date_range("1/1/2000", periods=4, freq="D")
9649 >>> df2 = pd.DataFrame(
9650 ... [
9651 ... [10, 50],
9652 ... [11, 60],
9653 ... [9, 40],
9654 ... [13, 100],
9655 ... [14, 50],
9656 ... [18, 100],
9657 ... [17, 40],
9658 ... [19, 50],
9659 ... ],
9660 ... columns=["price", "volume"],
9661 ... index=pd.MultiIndex.from_product([days, ["morning", "afternoon"]]),
9662 ... )
9663 >>> df2
9664 price volume
9665 2000-01-01 morning 10 50
9666 afternoon 11 60
9667 2000-01-02 morning 9 40
9668 afternoon 13 100
9669 2000-01-03 morning 14 50
9670 afternoon 18 100
9671 2000-01-04 morning 17 40
9672 afternoon 19 50
9673 >>> df2.resample("D", level=0).sum()
9674 price volume
9675 2000-01-01 21 110
9676 2000-01-02 22 140
9677 2000-01-03 32 150
9678 2000-01-04 36 90
9680 If you want to adjust the start of the bins based on a fixed timestamp:
9682 >>> start, end = "2000-10-01 23:30:00", "2000-10-02 00:30:00"
9683 >>> rng = pd.date_range(start, end, freq="7min")
9684 >>> ts = pd.Series(np.arange(len(rng)) * 3, index=rng)
9685 >>> ts
9686 2000-10-01 23:30:00 0
9687 2000-10-01 23:37:00 3
9688 2000-10-01 23:44:00 6
9689 2000-10-01 23:51:00 9
9690 2000-10-01 23:58:00 12
9691 2000-10-02 00:05:00 15
9692 2000-10-02 00:12:00 18
9693 2000-10-02 00:19:00 21
9694 2000-10-02 00:26:00 24
9695 Freq: 7min, dtype: int64
9697 >>> ts.resample("17min").sum()
9698 2000-10-01 23:14:00 0
9699 2000-10-01 23:31:00 9
9700 2000-10-01 23:48:00 21
9701 2000-10-02 00:05:00 54
9702 2000-10-02 00:22:00 24
9703 Freq: 17min, dtype: int64
9705 >>> ts.resample("17min", origin="epoch").sum()
9706 2000-10-01 23:18:00 0
9707 2000-10-01 23:35:00 18
9708 2000-10-01 23:52:00 27
9709 2000-10-02 00:09:00 39
9710 2000-10-02 00:26:00 24
9711 Freq: 17min, dtype: int64
9713 >>> ts.resample("17min", origin="2000-01-01").sum()
9714 2000-10-01 23:24:00 3
9715 2000-10-01 23:41:00 15
9716 2000-10-01 23:58:00 45
9717 2000-10-02 00:15:00 45
9718 Freq: 17min, dtype: int64
9720 If you want to adjust the start of the bins with an `offset` Timedelta, the two
9721 following lines are equivalent:
9723 >>> ts.resample("17min", origin="start").sum()
9724 2000-10-01 23:30:00 9
9725 2000-10-01 23:47:00 21
9726 2000-10-02 00:04:00 54
9727 2000-10-02 00:21:00 24
9728 Freq: 17min, dtype: int64
9730 >>> ts.resample("17min", offset="23h30min").sum()
9731 2000-10-01 23:30:00 9
9732 2000-10-01 23:47:00 21
9733 2000-10-02 00:04:00 54
9734 2000-10-02 00:21:00 24
9735 Freq: 17min, dtype: int64
9737 If you want to take the largest Timestamp as the end of the bins:
9739 >>> ts.resample("17min", origin="end").sum()
9740 2000-10-01 23:35:00 0
9741 2000-10-01 23:52:00 18
9742 2000-10-02 00:09:00 27
9743 2000-10-02 00:26:00 63
9744 Freq: 17min, dtype: int64
9746 In contrast with the `start_day`, you can use `end_day` to take the ceiling
9747 midnight of the largest Timestamp as the end of the bins and drop the bins
9748 not containing data:
9750 >>> ts.resample("17min", origin="end_day").sum()
9751 2000-10-01 23:38:00 3
9752 2000-10-01 23:55:00 15
9753 2000-10-02 00:12:00 45
9754 2000-10-02 00:29:00 45
9755 Freq: 17min, dtype: int64
9756 """
9757 from pandas.core.resample import get_resampler
9759 return get_resampler(
9760 cast("Series | DataFrame", self),
9761 freq=rule,
9762 label=label,
9763 closed=closed,
9764 convention=convention,
9765 key=on,
9766 level=level,
9767 origin=origin,
9768 offset=offset,
9769 group_keys=group_keys,
9770 )
9772 @final
9773 def rank(
9774 self,
9775 axis: Axis = 0,
9776 method: RankMethod = "average",
9777 numeric_only: bool = False,
9778 na_option: RankNaOption = "keep",
9779 ascending: bool = True,
9780 pct: bool = False,
9781 ) -> Self:
9782 """
9783 Compute numerical data ranks (1 through n) along axis.
9785 By default, equal values are assigned a rank that is the average of the
9786 ranks of those values.
9788 Parameters
9789 ----------
9790 axis : {0 or 'index', 1 or 'columns'}, default 0
9791 Index to direct ranking.
9792 For `Series` this parameter is unused and defaults to 0.
9793 method : {'average', 'min', 'max', 'first', 'dense'}, default 'average'
9794 How to rank the group of records that have the same value (i.e. ties):
9796 * average: average rank of the group
9797 * min: lowest rank in the group
9798 * max: highest rank in the group
9799 * first: ranks assigned in order they appear in the array
9800 * dense: like 'min', but rank always increases by 1 between groups.
9802 numeric_only : bool, default False
9803 For DataFrame objects, rank only numeric columns if set to True.
9805 .. versionchanged:: 2.0.0
9806 The default value of ``numeric_only`` is now ``False``.
9808 na_option : {'keep', 'top', 'bottom'}, default 'keep'
9809 How to rank NaN values:
9811 * keep: assign NaN rank to NaN values
9812 * top: assign lowest rank to NaN values
9813 * bottom: assign highest rank to NaN values
9815 ascending : bool, default True
9816 Whether or not the elements should be ranked in ascending order.
9817 pct : bool, default False
9818 Whether or not to display the returned rankings in percentile
9819 form.
9821 Returns
9822 -------
9823 same type as caller
9824 Return a Series or DataFrame with data ranks as values.
9826 See Also
9827 --------
9828 core.groupby.DataFrameGroupBy.rank : Rank of values within each group.
9829 core.groupby.SeriesGroupBy.rank : Rank of values within each group.
9831 Examples
9832 --------
9833 >>> df = pd.DataFrame(
9834 ... data={
9835 ... "Animal": ["cat", "penguin", "dog", "spider", "snake"],
9836 ... "Number_legs": [4, 2, 4, 8, np.nan],
9837 ... }
9838 ... )
9839 >>> df
9840 Animal Number_legs
9841 0 cat 4.0
9842 1 penguin 2.0
9843 2 dog 4.0
9844 3 spider 8.0
9845 4 snake NaN
9847 Ties are assigned the mean of the ranks (by default) for the group.
9849 >>> s = pd.Series(range(5), index=list("abcde"))
9850 >>> s["d"] = s["b"]
9851 >>> s.rank()
9852 a 1.0
9853 b 2.5
9854 c 4.0
9855 d 2.5
9856 e 5.0
9857 dtype: float64
9859 The following example shows how the method behaves with the above
9860 parameters:
9862 * default_rank: this is the default behaviour obtained without using
9863 any parameter.
9864 * max_rank: setting ``method = 'max'`` the records that have the
9865 same values are ranked using the highest rank (e.g.: since 'cat'
9866 and 'dog' are both in the 2nd and 3rd position, rank 3 is assigned.)
9867 * NA_bottom: choosing ``na_option = 'bottom'``, if there are records
9868 with NaN values they are placed at the bottom of the ranking.
9869 * pct_rank: when setting ``pct = True``, the ranking is expressed as
9870 percentile rank.
9872 >>> df["default_rank"] = df["Number_legs"].rank()
9873 >>> df["max_rank"] = df["Number_legs"].rank(method="max")
9874 >>> df["NA_bottom"] = df["Number_legs"].rank(na_option="bottom")
9875 >>> df["pct_rank"] = df["Number_legs"].rank(pct=True)
9876 >>> df
9877 Animal Number_legs default_rank max_rank NA_bottom pct_rank
9878 0 cat 4.0 2.5 3.0 2.5 0.625
9879 1 penguin 2.0 1.0 1.0 1.0 0.250
9880 2 dog 4.0 2.5 3.0 2.5 0.625
9881 3 spider 8.0 4.0 4.0 4.0 1.000
9882 4 snake NaN NaN NaN 5.0 NaN
9883 """
9884 axis_int = self._get_axis_number(axis)
9886 if na_option not in {"keep", "top", "bottom"}:
9887 msg = "na_option must be one of 'keep', 'top', or 'bottom'"
9888 raise ValueError(msg)
9890 def ranker(data):
9891 if data.ndim == 2:
9892 # i.e. DataFrame, we cast to ndarray
9893 values = data.values
9894 else:
9895 # i.e. Series, can dispatch to EA
9896 values = data._values
9898 if isinstance(values, ExtensionArray):
9899 ranks = values._rank(
9900 axis=axis_int,
9901 method=method,
9902 ascending=ascending,
9903 na_option=na_option,
9904 pct=pct,
9905 )
9906 else:
9907 ranks = algos.rank(
9908 values,
9909 axis=axis_int,
9910 method=method,
9911 ascending=ascending,
9912 na_option=na_option,
9913 pct=pct,
9914 )
9916 ranks_obj = self._constructor(ranks, **data._construct_axes_dict())
9917 return ranks_obj.__finalize__(self, method="rank")
9919 if numeric_only:
9920 if self.ndim == 1 and not is_numeric_dtype(self.dtype):
9921 # GH#47500
9922 raise TypeError(
9923 "Series.rank does not allow numeric_only=True with "
9924 "non-numeric dtype."
9925 )
9926 data = self._get_numeric_data()
9927 else:
9928 data = self
9930 return ranker(data)
9932 def compare(
9933 self,
9934 other: Self,
9935 align_axis: Axis = 1,
9936 keep_shape: bool = False,
9937 keep_equal: bool = False,
9938 result_names: Suffixes = ("self", "other"),
9939 ):
9940 """
9941 Compare to another Series/DataFrame and show the differences.
9943 Parameters
9944 ----------
9945 other : Series/DataFrame
9946 Object to compare with.
9948 align_axis : {0 or 'index', 1 or 'columns'}, default 1
9949 Determine which axis to align the comparison on.
9951 * 0, or 'index' : Resulting differences are stacked vertically
9952 with rows drawn alternately from self and other.
9953 * 1, or 'columns' : Resulting differences are aligned horizontally
9954 with columns drawn alternately from self and other.
9956 keep_shape : bool, default False
9957 If true, all rows and columns are kept.
9958 Otherwise, only the ones with different values are kept.
9960 keep_equal : bool, default False
9961 If true, the result keeps values that are equal.
9962 Otherwise, equal values are shown as NaNs.
9964 result_names : tuple, default ('self', 'other')
9965 Set the dataframes names in the comparison.
9966 """
9967 if type(self) is not type(other):
9968 cls_self, cls_other = type(self).__name__, type(other).__name__
9969 raise TypeError(
9970 f"can only compare '{cls_self}' (not '{cls_other}') with '{cls_self}'"
9971 )
9973 # error: Unsupported left operand type for & ("Self")
9974 mask = ~((self == other) | (self.isna() & other.isna())) # type: ignore[operator]
9975 mask.fillna(True, inplace=True)
9977 if not keep_equal:
9978 self = self.where(mask)
9979 other = other.where(mask)
9981 if not keep_shape:
9982 if isinstance(self, ABCDataFrame):
9983 cmask = mask.any()
9984 rmask = mask.any(axis=1)
9985 self = self.loc[rmask, cmask]
9986 other = other.loc[rmask, cmask]
9987 else:
9988 self = self[mask]
9989 other = other[mask]
9990 if not isinstance(result_names, tuple):
9991 raise TypeError(
9992 f"Passing 'result_names' as a {type(result_names)} is not "
9993 "supported. Provide 'result_names' as a tuple instead."
9994 )
9996 if align_axis in (1, "columns"): # This is needed for Series
9997 axis = 1
9998 else:
9999 axis = self._get_axis_number(align_axis)
10001 # error: List item 0 has incompatible type "NDFrame"; expected
10002 # "Union[Series, DataFrame]"
10003 diff = concat(
10004 [self, other], # type: ignore[list-item]
10005 axis=axis,
10006 keys=result_names,
10007 )
10009 if axis >= self.ndim:
10010 # No need to reorganize data if stacking on new axis
10011 # This currently applies for stacking two Series on columns
10012 return diff
10014 ax = diff._get_axis(axis)
10015 ax_names = np.array(ax.names)
10017 # set index names to positions to avoid confusion
10018 ax.names = np.arange(len(ax_names))
10020 # bring self-other to inner level
10021 order = [*range(1, ax.nlevels), 0]
10022 if isinstance(diff, ABCDataFrame):
10023 diff = diff.reorder_levels(order, axis=axis)
10024 else:
10025 diff = diff.reorder_levels(order)
10027 # restore the index names in order
10028 diff._get_axis(axis=axis).names = ax_names[order]
10030 # reorder axis to keep things organized
10031 indices = (
10032 np.arange(diff.shape[axis])
10033 .reshape([2, diff.shape[axis] // 2])
10034 .T.reshape(-1)
10035 )
10036 diff = diff.take(indices, axis=axis)
10038 return diff
10040 @final
10041 def align(
10042 self,
10043 other: NDFrameT,
10044 join: AlignJoin = "outer",
10045 axis: Axis | None = None,
10046 level: Level | None = None,
10047 copy: bool | lib.NoDefault = lib.no_default,
10048 fill_value: Hashable | None = None,
10049 ) -> tuple[Self, NDFrameT]:
10050 """
10051 Align two objects on their axes with the specified join method.
10053 Join method is specified for each axis Index.
10055 Parameters
10056 ----------
10057 other : DataFrame or Series
10058 The object to align with.
10059 join : {'outer', 'inner', 'left', 'right'}, default 'outer'
10060 Type of alignment to be performed.
10062 * left: use only keys from left frame, preserve key order.
10063 * right: use only keys from right frame, preserve key order.
10064 * outer: use union of keys from both frames, sort keys lexicographically.
10065 * inner: use intersection of keys from both frames,
10066 preserve the order of the left keys.
10068 axis : allowed axis of the other object, default None
10069 Align on index (0), columns (1), or both (None).
10070 level : int or level name, default None
10071 Broadcast across a level, matching Index values on the
10072 passed MultiIndex level.
10073 copy : bool, default False
10074 This keyword is now ignored; changing its value will have no
10075 impact on the method.
10077 .. deprecated:: 3.0.0
10079 This keyword is ignored and will be removed in pandas 4.0. Since
10080 pandas 3.0, this method always returns a new object using a lazy
10081 copy mechanism that defers copies until necessary
10082 (Copy-on-Write). See the `user guide on Copy-on-Write
10083 <https://pandas.pydata.org/docs/dev/user_guide/migration.html>`__
10084 for more details.
10086 fill_value : scalar, default np.nan
10087 Value to use for missing values. Defaults to NaN, but can be any
10088 "compatible" value.
10090 Returns
10091 -------
10092 tuple of (Series/DataFrame, type of other)
10093 Aligned objects.
10095 See Also
10096 --------
10097 Series.align : Align two objects on their axes with specified join method.
10098 DataFrame.align : Align two objects on their axes with specified join method.
10100 Examples
10101 --------
10102 >>> df = pd.DataFrame(
10103 ... [[1, 2, 3, 4], [6, 7, 8, 9]], columns=["D", "B", "E", "A"], index=[1, 2]
10104 ... )
10105 >>> other = pd.DataFrame(
10106 ... [[10, 20, 30, 40], [60, 70, 80, 90], [600, 700, 800, 900]],
10107 ... columns=["A", "B", "C", "D"],
10108 ... index=[2, 3, 4],
10109 ... )
10110 >>> df
10111 D B E A
10112 1 1 2 3 4
10113 2 6 7 8 9
10114 >>> other
10115 A B C D
10116 2 10 20 30 40
10117 3 60 70 80 90
10118 4 600 700 800 900
10120 Align on columns:
10122 >>> left, right = df.align(other, join="outer", axis=1)
10123 >>> left
10124 A B C D E
10125 1 4 2 NaN 1 3
10126 2 9 7 NaN 6 8
10127 >>> right
10128 A B C D E
10129 2 10 20 30 40 NaN
10130 3 60 70 80 90 NaN
10131 4 600 700 800 900 NaN
10133 We can also align on the index:
10135 >>> left, right = df.align(other, join="outer", axis=0)
10136 >>> left
10137 D B E A
10138 1 1.0 2.0 3.0 4.0
10139 2 6.0 7.0 8.0 9.0
10140 3 NaN NaN NaN NaN
10141 4 NaN NaN NaN NaN
10142 >>> right
10143 A B C D
10144 1 NaN NaN NaN NaN
10145 2 10.0 20.0 30.0 40.0
10146 3 60.0 70.0 80.0 90.0
10147 4 600.0 700.0 800.0 900.0
10149 Finally, the default `axis=None` will align on both index and columns:
10151 >>> left, right = df.align(other, join="outer", axis=None)
10152 >>> left
10153 A B C D E
10154 1 4.0 2.0 NaN 1.0 3.0
10155 2 9.0 7.0 NaN 6.0 8.0
10156 3 NaN NaN NaN NaN NaN
10157 4 NaN NaN NaN NaN NaN
10158 >>> right
10159 A B C D E
10160 1 NaN NaN NaN NaN NaN
10161 2 10.0 20.0 30.0 40.0 NaN
10162 3 60.0 70.0 80.0 90.0 NaN
10163 4 600.0 700.0 800.0 900.0 NaN
10164 """
10165 self._check_copy_deprecation(copy)
10167 _right: DataFrame | Series
10168 if axis is not None:
10169 axis = self._get_axis_number(axis)
10171 # GH#65056 - rewrite the date-inference deprecation with a message
10172 # appropriate for alignment operations
10173 with rewrite_warning(
10174 target_message="datetime.date",
10175 target_category=Pandas4Warning,
10176 new_message=(
10177 "Alignment of a DataFrame/Series with a DatetimeIndex "
10178 "and a DataFrame/Series with an object-dtype Index of "
10179 "datetime.date objects is deprecated. Convert the "
10180 "datetime.date Index to DatetimeIndex using "
10181 "pd.to_datetime before performing this operation."
10182 ),
10183 ):
10184 if isinstance(other, ABCDataFrame):
10185 left, _right, join_index = self._align_frame(
10186 other,
10187 join=join,
10188 axis=axis,
10189 level=level,
10190 fill_value=fill_value,
10191 )
10193 elif isinstance(other, ABCSeries):
10194 left, _right, join_index = self._align_series(
10195 other,
10196 join=join,
10197 axis=axis,
10198 level=level,
10199 fill_value=fill_value,
10200 )
10201 else: # pragma: no cover
10202 raise TypeError(f"unsupported type: {type(other)}")
10204 right = cast("NDFrameT", _right)
10205 if self.ndim == 1 or axis == 0:
10206 # If we are aligning timezone-aware DatetimeIndexes and the timezones
10207 # do not match, convert both to UTC.
10208 if isinstance(left.index.dtype, DatetimeTZDtype):
10209 if left.index.tz != right.index.tz:
10210 if join_index is not None:
10211 # GH#33671 copy to ensure we don't change the index on
10212 # our original Series
10213 left = left.copy(deep=False)
10214 right = right.copy(deep=False)
10215 left.index = join_index
10216 right.index = join_index
10218 left = left.__finalize__(self)
10219 right = right.__finalize__(other)
10220 return left, right
10222 @final
10223 def _align_frame(
10224 self,
10225 other: DataFrame,
10226 join: AlignJoin = "outer",
10227 axis: Axis | None = None,
10228 level=None,
10229 fill_value=None,
10230 ) -> tuple[Self, DataFrame, Index | None]:
10231 # defaults
10232 join_index, join_columns = None, None
10233 ilidx, iridx = None, None
10234 clidx, cridx = None, None
10236 is_series = isinstance(self, ABCSeries)
10238 if (axis is None or axis == 0) and not self.index.equals(other.index):
10239 join_index, ilidx, iridx = self.index.join(
10240 other.index, how=join, level=level, return_indexers=True
10241 )
10243 if (
10244 (axis is None or axis == 1)
10245 and not is_series
10246 and not self.columns.equals(other.columns)
10247 ):
10248 join_columns, clidx, cridx = self.columns.join(
10249 other.columns, how=join, level=level, return_indexers=True
10250 )
10252 if is_series:
10253 reindexers = {0: [join_index, ilidx]}
10254 else:
10255 reindexers = {0: [join_index, ilidx], 1: [join_columns, clidx]}
10257 left = self._reindex_with_indexers(
10258 reindexers, fill_value=fill_value, allow_dups=True
10259 )
10260 # other must be always DataFrame
10261 right = other._reindex_with_indexers(
10262 {0: [join_index, iridx], 1: [join_columns, cridx]},
10263 fill_value=fill_value,
10264 allow_dups=True,
10265 )
10266 return left, right, join_index
10268 @final
10269 def _align_series(
10270 self,
10271 other: Series,
10272 join: AlignJoin = "outer",
10273 axis: Axis | None = None,
10274 level=None,
10275 fill_value=None,
10276 ) -> tuple[Self, Series, Index | None]:
10277 is_series = isinstance(self, ABCSeries)
10279 if (not is_series and axis is None) or axis not in [None, 0, 1]:
10280 raise ValueError("Must specify axis=0 or 1")
10282 if is_series and axis == 1:
10283 raise ValueError("cannot align series to a series other than axis 0")
10285 # series/series compat, other must always be a Series
10286 if not axis:
10287 # equal
10288 if self.index.equals(other.index):
10289 join_index, lidx, ridx = None, None, None
10290 else:
10291 join_index, lidx, ridx = self.index.join(
10292 other.index, how=join, level=level, return_indexers=True
10293 )
10295 if is_series:
10296 left = self._reindex_indexer(join_index, lidx)
10297 elif lidx is None or join_index is None:
10298 left = self.copy(deep=False)
10299 else:
10300 new_mgr = self._mgr.reindex_indexer(join_index, lidx, axis=1)
10301 left = self._constructor_from_mgr(new_mgr, axes=new_mgr.axes)
10303 right = other._reindex_indexer(join_index, ridx)
10305 else:
10306 # one has > 1 ndim
10307 fdata = self._mgr
10308 join_index = self.axes[1]
10309 lidx, ridx = None, None
10310 if not join_index.equals(other.index):
10311 join_index, lidx, ridx = join_index.join(
10312 other.index, how=join, level=level, return_indexers=True
10313 )
10315 if lidx is not None:
10316 bm_axis = self._get_block_manager_axis(1)
10317 fdata = fdata.reindex_indexer(join_index, lidx, axis=bm_axis)
10319 left = self._constructor_from_mgr(fdata, axes=fdata.axes)
10321 right = other._reindex_indexer(join_index, ridx)
10323 # fill
10324 fill_na = notna(fill_value)
10325 if fill_na:
10326 left = left.fillna(fill_value)
10327 right = right.fillna(fill_value)
10329 return left, right, join_index
10331 @final
10332 def _where(
10333 self,
10334 cond,
10335 other=lib.no_default,
10336 *,
10337 inplace: bool = False,
10338 axis: Axis | None = None,
10339 level=None,
10340 ) -> Self:
10341 """
10342 Equivalent to public method `where`, except that `other` is not
10343 applied as a function even if callable. Used in __setitem__.
10344 """
10345 inplace = validate_bool_kwarg(inplace, "inplace")
10347 if axis is not None:
10348 axis = self._get_axis_number(axis)
10350 fill_value = bool(inplace)
10352 # align the cond to same shape as myself
10353 cond = common.apply_if_callable(cond, self)
10354 if isinstance(cond, NDFrame):
10355 # CoW: Make sure reference is not kept alive
10356 if cond.ndim == 1 and self.ndim == 2:
10357 if axis == 1:
10358 # GH#58190 broadcast cond along columns
10359 cond = cond._constructor_expanddim(
10360 dict.fromkeys(range(len(self)), cond),
10361 copy=False,
10362 ).T
10363 cond.index = self.index
10364 else:
10365 cond = cond._constructor_expanddim(
10366 dict.fromkeys(range(len(self.columns)), cond),
10367 copy=False,
10368 )
10369 cond.columns = self.columns
10370 if _is_np_bool_backed(cond) and self.ndim == 2:
10371 # GH#51547 a bool cond that needs reindexing would otherwise be
10372 # cast to object and cast back by the fillna/infer_objects
10373 # below. Only safe for ndim==2: _align_series applies
10374 # fill_value via fillna to *both* objects, so it would alter
10375 # self. Only safe for bool cond: for other dtypes a bool
10376 # fill_value is an incompatible reindex fill.
10377 cond = cond.align(self, join="right", fill_value=fill_value)[0]
10378 else:
10379 cond = cond.align(self, join="right")[0]
10380 else:
10381 if not hasattr(cond, "shape"):
10382 cond = np.asanyarray(cond)
10383 if cond.shape != self.shape:
10384 raise ValueError("Array conditional must be same shape as self")
10385 cond = self._constructor(cond, **self._construct_axes_dict(), copy=False)
10387 # make sure we are boolean
10388 if not _is_np_bool_backed(cond):
10389 with warnings.catch_warnings():
10390 # GH#45153 suppress Pandas4Warning from fillna with
10391 # incompatible value; if cond is not boolean, the dtype
10392 # check below will raise TypeError anyway.
10393 warnings.filterwarnings("ignore", ".*fill value.*", Pandas4Warning)
10394 cond = cond.fillna(fill_value)
10395 cond = cond.infer_objects()
10397 msg = "Boolean array expected for the condition, not {dtype}"
10399 if not cond.empty:
10400 if not isinstance(cond, ABCDataFrame):
10401 # This is a single-dimensional object.
10402 if not is_bool_dtype(cond):
10403 raise TypeError(msg.format(dtype=cond.dtype))
10404 else:
10405 for block in cond._mgr.blocks:
10406 if not is_bool_dtype(block.dtype):
10407 raise TypeError(msg.format(dtype=block.dtype))
10408 if cond._mgr.any_extension_types:
10409 # GH51574: avoid object ndarray conversion later on
10410 cond = cond._constructor(
10411 cond.to_numpy(dtype=bool, na_value=fill_value),
10412 **cond._construct_axes_dict(),
10413 )
10414 else:
10415 # GH#21947 we have an empty DataFrame/Series, could be object-dtype
10416 cond = cond.astype(bool)
10418 cond_for_ea = cond
10419 cond = -cond if inplace else cond
10420 if not cond._info_axis.equals(self._info_axis):
10421 cond = cond.reindex(self._info_axis, axis=self._info_axis_number)
10423 # try to align with other
10424 if isinstance(other, NDFrame):
10425 # align with me
10426 if other.ndim <= self.ndim:
10427 # CoW: Make sure reference is not kept alive
10428 other = self.align(
10429 other,
10430 join="left",
10431 axis=axis,
10432 level=level,
10433 fill_value=None,
10434 )[1]
10436 # if we are NOT aligned, raise as we cannot where index
10437 if axis is None and not other._indexed_same(self):
10438 raise InvalidIndexError(
10439 "Cannot align with an object that has duplicate labels"
10440 )
10442 if other.ndim < self.ndim:
10443 other = other._values
10444 if isinstance(other, np.ndarray):
10445 # TODO(EA2D): could also do this for NDArrayBackedEA cases?
10446 if axis == 0:
10447 other = np.reshape(other, (-1, 1))
10448 elif axis == 1:
10449 other = np.reshape(other, (1, -1))
10451 other = np.broadcast_to(other, self.shape)
10452 else:
10453 # GH#38729, GH#62038 avoid lossy casting or object-casting
10454 if axis == 0:
10455 res_cols = [
10456 self.iloc[:, i]._where(
10457 cond_for_ea.iloc[:, i],
10458 other,
10459 )
10460 for i in range(self.shape[1])
10461 ]
10462 elif axis == 1:
10463 # TODO: can we use a zero-copy alternative to "repeat"?
10464 res_cols = [
10465 self.iloc[:, i]._where(
10466 cond_for_ea.iloc[:, i],
10467 other[i : i + 1].repeat(len(self)),
10468 )
10469 for i in range(self.shape[1])
10470 ]
10471 res = self._constructor(dict(enumerate(res_cols)))
10472 res.index = self.index
10473 res.columns = self.columns
10474 if inplace:
10475 self._update_inplace(res)
10476 return self
10477 return res.__finalize__(self)
10479 # slice me out of the other
10480 else:
10481 raise NotImplementedError(
10482 "cannot align with a higher dimensional NDFrame"
10483 )
10485 elif not isinstance(other, (MultiIndex, NDFrame)):
10486 # mainly just catching Index here
10487 other = extract_array(other, extract_numpy=True, extract_range=True)
10488 if (
10489 self.ndim == 1
10490 and is_list_like(other)
10491 # a dict is keyed and a set unordered, so neither lines up by position
10492 and not isinstance(other, (np.ndarray, ExtensionArray, set, frozenset))
10493 and not is_dict_like(other)
10494 # outside numeric and bool dtypes a tuple is one element, as
10495 # for object dtype (GH#37681)
10496 and (
10497 not isinstance(other, tuple)
10498 or is_numeric_dtype(self.dtype)
10499 or is_bool_dtype(self.dtype)
10500 )
10501 ):
10502 # GH#63842 line up a list against the mask like an ndarray
10503 other = common.asarray_tuplesafe(other)
10505 if isinstance(other, (np.ndarray, ExtensionArray)):
10506 if self.ndim == 1 and other.ndim == 1 and len(other) == 1:
10507 # broadcast like a scalar (GH#2745, GH#4192)
10508 other = other.repeat(len(self))
10510 if other.shape != self.shape:
10511 if self.ndim != 1:
10512 raise ValueError(
10513 "other must be the same shape as self when an ndarray"
10514 )
10515 if other.ndim == 1 and not (inplace and len(other) == cond.sum()):
10516 # inplace with one value per selected position is treated
10517 # like __setitem__ (GH#3235)
10518 raise ValueError(
10519 f"Length of values ({len(other)}) does not match length "
10520 f"of index ({len(self)})"
10521 )
10523 # we are the same shape, so create an actual object for alignment
10524 else:
10525 other = self._constructor(
10526 other, **self._construct_axes_dict(), copy=False
10527 )
10529 if axis is None:
10530 axis = 0
10532 other_ndim = getattr(other, "ndim", 0)
10533 if self.ndim == other_ndim:
10534 align = True
10535 else:
10536 # GH#58190 scalar other (ndim=0) should never be aligned
10537 align = other_ndim >= 1 and self._get_axis_number(axis) == 1
10539 if inplace:
10540 # we may have different type blocks come out of putmask, so
10541 # reconstruct the block manager
10543 new_data = self._mgr.putmask(mask=cond, new=other, align=align)
10544 result = self._constructor_from_mgr(new_data, axes=new_data.axes)
10545 self._update_inplace(result)
10546 return self
10548 else:
10549 new_data = self._mgr.where(
10550 other=other,
10551 cond=cond,
10552 align=align,
10553 )
10554 result = self._constructor_from_mgr(new_data, axes=new_data.axes)
10555 return result.__finalize__(self)
10557 @final
10558 def where(
10559 self,
10560 cond,
10561 other=lib.no_default,
10562 *,
10563 inplace: bool = False,
10564 axis: Axis | None = None,
10565 level: Level | None = None,
10566 ) -> Self:
10567 """
10568 Replace values where the condition is False.
10570 This method allows conditional replacement of values. Where the
10571 condition evaluates to True, the original values are retained; where
10572 it evaluates to False, values are replaced with corresponding entries
10573 from ``other``.
10575 Parameters
10576 ----------
10577 cond : bool Series/DataFrame, array-like, or callable
10578 Where `cond` is True, keep the original value. Where
10579 False, replace with corresponding value from `other`.
10580 If `cond` is callable, it is computed on the Series/DataFrame and
10581 should return boolean Series/DataFrame or array. The callable must
10582 not change input Series/DataFrame (though pandas doesn't check it).
10583 other : scalar, array-like, Series/DataFrame, Index, or callable
10584 Entries where `cond` is False are replaced with
10585 corresponding value from `other`.
10586 If other is callable, it is computed on the Series/DataFrame and
10587 should return scalar or Series/DataFrame. The callable must not
10588 change input Series/DataFrame (though pandas doesn't check it).
10589 If not specified, entries will be filled with the corresponding
10590 NULL value (``np.nan`` for numpy dtypes, ``pd.NA`` for extension
10591 dtypes).
10592 inplace : bool, default False
10593 Whether to perform the operation in place on the data.
10594 axis : int, default None
10595 Alignment axis, used only when aligning `other` with the
10596 calling object; it has no effect on the alignment of `cond`,
10597 which is always aligned on the calling object's labels. For
10598 `Series` this parameter is unused and defaults to 0.
10599 level : int, default None
10600 Alignment level, used only when aligning `other` with the
10601 calling object; it has no effect on the alignment of `cond`.
10603 Returns
10604 -------
10605 Series or DataFrame
10606 When applied to a Series, the function will return a Series,
10607 and when applied to a DataFrame, it will return a DataFrame.
10609 See Also
10610 --------
10611 :func:`DataFrame.mask` : Return an object of same shape as caller.
10612 :func:`Series.mask` : Return an object of same shape as caller.
10614 Notes
10615 -----
10616 The where method is an application of the if-then idiom. For each
10617 element in the caller, if ``cond`` is ``True`` the
10618 element is used; otherwise the corresponding element from
10619 ``other`` is used. If the axis of ``cond`` does not align with
10620 the caller Series/DataFrame, the values of ``cond`` on misaligned
10621 index positions will be filled with False.
10623 The signature for :func:`Series.where` or
10624 :func:`DataFrame.where` differs from :func:`numpy.where`.
10625 Roughly ``df1.where(m, df2)`` is equivalent to ``np.where(m, df1, df2)``.
10627 For further details and examples see the ``where`` documentation in
10628 :ref:`indexing <indexing.where_mask>`.
10630 The dtype of the object takes precedence. The fill value is casted to
10631 the object's dtype, if this can be done losslessly.
10633 Examples
10634 --------
10635 >>> s = pd.Series(range(5))
10636 >>> s.where(s > 0)
10637 0 NaN
10638 1 1.0
10639 2 2.0
10640 3 3.0
10641 4 4.0
10642 dtype: float64
10643 >>> s.mask(s > 0)
10644 0 0.0
10645 1 NaN
10646 2 NaN
10647 3 NaN
10648 4 NaN
10649 dtype: float64
10651 >>> s = pd.Series(range(5))
10652 >>> t = pd.Series([True, False])
10653 >>> s.where(t, 99)
10654 0 0
10655 1 99
10656 2 99
10657 3 99
10658 4 99
10659 dtype: int64
10660 >>> s.mask(t, 99)
10661 0 99
10662 1 1
10663 2 99
10664 3 99
10665 4 99
10666 dtype: int64
10668 >>> s.where(s > 1, 10)
10669 0 10
10670 1 10
10671 2 2
10672 3 3
10673 4 4
10674 dtype: int64
10675 >>> s.mask(s > 1, 10)
10676 0 0
10677 1 1
10678 2 10
10679 3 10
10680 4 10
10681 dtype: int64
10683 >>> df = pd.DataFrame(np.arange(10).reshape(-1, 2), columns=["A", "B"])
10684 >>> df
10685 A B
10686 0 0 1
10687 1 2 3
10688 2 4 5
10689 3 6 7
10690 4 8 9
10691 >>> m = df % 3 == 0
10692 >>> df.where(m, -df)
10693 A B
10694 0 0 -1
10695 1 -2 3
10696 2 -4 -5
10697 3 6 -7
10698 4 -8 9
10699 >>> df.where(m, -df) == np.where(m, df, -df)
10700 A B
10701 0 True True
10702 1 True True
10703 2 True True
10704 3 True True
10705 4 True True
10706 >>> df.where(m, -df) == df.mask(~m, -df)
10707 A B
10708 0 True True
10709 1 True True
10710 2 True True
10711 3 True True
10712 4 True True
10713 """
10714 inplace = validate_bool_kwarg(inplace, "inplace")
10715 if inplace:
10716 if not CHAINED_WARNING_DISABLED:
10717 if sys.getrefcount(
10718 self
10719 ) <= REF_COUNT_METHOD and not common.is_local_in_caller_frame(self):
10720 warnings.warn(
10721 _chained_assignment_method_msg,
10722 ChainedAssignmentError,
10723 stacklevel=2,
10724 )
10726 other = common.apply_if_callable(other, self)
10727 return self._where(cond, other, inplace=inplace, axis=axis, level=level)
10729 @final
10730 def mask(
10731 self,
10732 cond,
10733 other=lib.no_default,
10734 *,
10735 inplace: bool = False,
10736 axis: Axis | None = None,
10737 level: Level | None = None,
10738 ) -> Self:
10739 """
10740 Replace values where the condition is True.
10742 Where ``cond`` is True, the result takes the value from
10743 ``other``; where False, it keeps the original value. Inverse of
10744 :meth:`where`. Useful for replacing invalid or sentinel values.
10746 Parameters
10747 ----------
10748 cond : bool Series/DataFrame, array-like, or callable
10749 Where `cond` is False, keep the original value. Where
10750 True, replace with corresponding value from `other`.
10751 If `cond` is callable, it is computed on the Series/DataFrame and
10752 should return boolean Series/DataFrame or array. The callable must
10753 not change input Series/DataFrame (though pandas doesn't check it).
10754 other : scalar, Series/DataFrame, or callable
10755 Entries where `cond` is True are replaced with
10756 corresponding value from `other`.
10757 If other is callable, it is computed on the Series/DataFrame and
10758 should return scalar or Series/DataFrame. The callable must not
10759 change input Series/DataFrame (though pandas doesn't check it).
10760 If not specified, entries will be filled with the corresponding
10761 NULL value (``np.nan`` for numpy dtypes, ``pd.NA`` for extension
10762 dtypes).
10763 inplace : bool, default False
10764 Whether to perform the operation in place on the data.
10765 axis : int, default None
10766 Alignment axis, used only when aligning `other` with the
10767 calling object; it has no effect on the alignment of `cond`,
10768 which is always aligned on the calling object's labels. For
10769 `Series` this parameter is unused and defaults to 0.
10770 level : int, default None
10771 Alignment level, used only when aligning `other` with the
10772 calling object; it has no effect on the alignment of `cond`.
10774 Returns
10775 -------
10776 Series or DataFrame
10777 When applied to a Series, the function will return a Series,
10778 and when applied to a DataFrame, it will return a DataFrame.
10780 See Also
10781 --------
10782 :func:`DataFrame.where` : Return an object of same shape as caller.
10783 :func:`Series.where` : Return an object of same shape as caller.
10785 Notes
10786 -----
10787 The mask method is an application of the if-then idiom. For each
10788 element in the caller, if ``cond`` is ``False`` the
10789 element is used; otherwise the corresponding element from
10790 ``other`` is used. If the axis of ``cond`` does not align with
10791 the caller Series/DataFrame, the values of ``cond`` on misaligned
10792 index positions will be filled with True.
10794 The signature for :func:`Series.where` or
10795 :func:`DataFrame.where` differs from :func:`numpy.where`.
10796 Roughly ``df1.where(m, df2)`` is equivalent to ``np.where(m, df1, df2)``.
10798 For further details and examples see the ``mask`` documentation in
10799 :ref:`indexing <indexing.where_mask>`.
10801 The dtype of the object takes precedence. The fill value is casted to
10802 the object's dtype, if this can be done losslessly.
10804 Examples
10805 --------
10806 >>> s = pd.Series(range(5))
10807 >>> s.where(s > 0)
10808 0 NaN
10809 1 1.0
10810 2 2.0
10811 3 3.0
10812 4 4.0
10813 dtype: float64
10814 >>> s.mask(s > 0)
10815 0 0.0
10816 1 NaN
10817 2 NaN
10818 3 NaN
10819 4 NaN
10820 dtype: float64
10822 >>> s = pd.Series(range(5))
10823 >>> t = pd.Series([True, False])
10824 >>> s.where(t, 99)
10825 0 0
10826 1 99
10827 2 99
10828 3 99
10829 4 99
10830 dtype: int64
10831 >>> s.mask(t, 99)
10832 0 99
10833 1 1
10834 2 99
10835 3 99
10836 4 99
10837 dtype: int64
10839 >>> s.where(s > 1, 10)
10840 0 10
10841 1 10
10842 2 2
10843 3 3
10844 4 4
10845 dtype: int64
10846 >>> s.mask(s > 1, 10)
10847 0 0
10848 1 1
10849 2 10
10850 3 10
10851 4 10
10852 dtype: int64
10854 >>> df = pd.DataFrame(np.arange(10).reshape(-1, 2), columns=["A", "B"])
10855 >>> df
10856 A B
10857 0 0 1
10858 1 2 3
10859 2 4 5
10860 3 6 7
10861 4 8 9
10862 >>> m = df % 3 == 0
10863 >>> df.where(m, -df)
10864 A B
10865 0 0 -1
10866 1 -2 3
10867 2 -4 -5
10868 3 6 -7
10869 4 -8 9
10870 >>> df.where(m, -df) == np.where(m, df, -df)
10871 A B
10872 0 True True
10873 1 True True
10874 2 True True
10875 3 True True
10876 4 True True
10877 >>> df.where(m, -df) == df.mask(~m, -df)
10878 A B
10879 0 True True
10880 1 True True
10881 2 True True
10882 3 True True
10883 4 True True
10884 """
10885 inplace = validate_bool_kwarg(inplace, "inplace")
10886 if inplace:
10887 if not CHAINED_WARNING_DISABLED:
10888 if sys.getrefcount(
10889 self
10890 ) <= REF_COUNT_METHOD and not common.is_local_in_caller_frame(self):
10891 warnings.warn(
10892 _chained_assignment_method_msg,
10893 ChainedAssignmentError,
10894 stacklevel=2,
10895 )
10897 cond = common.apply_if_callable(cond, self)
10898 other = common.apply_if_callable(other, self)
10900 # see gh-21891
10901 if not hasattr(cond, "__invert__"):
10902 cond = np.array(cond)
10904 return self._where(
10905 ~cond,
10906 other=other,
10907 inplace=inplace,
10908 axis=axis,
10909 level=level,
10910 )
10912 def shift(
10913 self,
10914 periods: int | Sequence[int] = 1,
10915 freq=None,
10916 axis: Axis = 0,
10917 fill_value: Hashable = lib.no_default,
10918 suffix: str | None = None,
10919 ) -> Self | DataFrame:
10920 """
10921 Shift index by desired number of periods with an optional time `freq`.
10923 When `freq` is not passed, shift the index without realigning the data.
10924 If `freq` is passed (in this case, the index must be date or datetime,
10925 or it will raise a `NotImplementedError`), the index will be
10926 increased using the periods and the `freq`. `freq` can be inferred
10927 when specified as "infer" as long as either freq or inferred_freq
10928 attribute is set in the index.
10930 Parameters
10931 ----------
10932 periods : int or Sequence
10933 Number of periods to shift. Can be positive or negative.
10934 If an iterable of ints, the data will be shifted once by each int.
10935 This is equivalent to shifting by one value at a time and
10936 concatenating all resulting frames. The resulting columns will have
10937 the shift suffixed to their column names. For multiple periods,
10938 axis must not be 1.
10939 freq : DateOffset, tseries.offsets, timedelta, or str, optional
10940 Offset to use from the tseries module or time rule (e.g. 'EOM').
10941 If `freq` is specified then the index values are shifted but the
10942 data is not realigned. That is, use `freq` if you would like to
10943 extend the index when shifting and preserve the original data.
10944 If `freq` is specified as "infer" then it will be inferred from
10945 the freq or inferred_freq attributes of the index. If neither of
10946 those attributes exist, a ValueError is thrown.
10947 axis : {0 or 'index', 1 or 'columns', None}, default None
10948 Shift direction. For `Series` this parameter is unused and defaults to 0.
10949 fill_value : object, optional
10950 The scalar value to use for newly introduced missing values.
10951 the default depends on the dtype of `self`.
10952 For Boolean and numeric NumPy data types, ``np.nan`` is used.
10953 For datetime, timedelta, or period data, etc. :attr:`NaT` is used.
10954 For extension dtypes, ``self.dtype.na_value`` is used.
10955 suffix : str, optional
10956 If str and periods is an iterable, this is added after the column
10957 name and before the shift value for each shifted column name.
10959 Returns
10960 -------
10961 Series/DataFrame
10962 Copy of input object, shifted.
10964 See Also
10965 --------
10966 Index.shift : Shift values of Index.
10967 DatetimeIndex.shift : Shift values of DatetimeIndex.
10968 PeriodIndex.shift : Shift values of PeriodIndex.
10970 Examples
10971 --------
10972 >>> df = pd.DataFrame(
10973 ... [[10, 13, 17], [20, 23, 27], [15, 18, 22], [30, 33, 37], [45, 48, 52]],
10974 ... columns=["Col1", "Col2", "Col3"],
10975 ... index=pd.date_range("2020-01-01", "2020-01-05"),
10976 ... )
10977 >>> df
10978 Col1 Col2 Col3
10979 2020-01-01 10 13 17
10980 2020-01-02 20 23 27
10981 2020-01-03 15 18 22
10982 2020-01-04 30 33 37
10983 2020-01-05 45 48 52
10985 >>> df.shift(periods=3)
10986 Col1 Col2 Col3
10987 2020-01-01 NaN NaN NaN
10988 2020-01-02 NaN NaN NaN
10989 2020-01-03 NaN NaN NaN
10990 2020-01-04 10.0 13.0 17.0
10991 2020-01-05 20.0 23.0 27.0
10993 >>> df.shift(periods=1, axis="columns")
10994 Col1 Col2 Col3
10995 2020-01-01 NaN 10 13
10996 2020-01-02 NaN 20 23
10997 2020-01-03 NaN 15 18
10998 2020-01-04 NaN 30 33
10999 2020-01-05 NaN 45 48
11001 >>> df.shift(periods=3, fill_value=0)
11002 Col1 Col2 Col3
11003 2020-01-01 0 0 0
11004 2020-01-02 0 0 0
11005 2020-01-03 0 0 0
11006 2020-01-04 10 13 17
11007 2020-01-05 20 23 27
11009 >>> df.shift(periods=3, freq="D")
11010 Col1 Col2 Col3
11011 2020-01-04 10 13 17
11012 2020-01-05 20 23 27
11013 2020-01-06 15 18 22
11014 2020-01-07 30 33 37
11015 2020-01-08 45 48 52
11017 >>> df.shift(periods=3, freq="infer")
11018 Col1 Col2 Col3
11019 2020-01-04 10 13 17
11020 2020-01-05 20 23 27
11021 2020-01-06 15 18 22
11022 2020-01-07 30 33 37
11023 2020-01-08 45 48 52
11025 >>> df["Col1"].shift(periods=[0, 1, 2])
11026 Col1_0 Col1_1 Col1_2
11027 2020-01-01 10 NaN NaN
11028 2020-01-02 20 10.0 NaN
11029 2020-01-03 15 20.0 10.0
11030 2020-01-04 30 15.0 20.0
11031 2020-01-05 45 30.0 15.0
11032 """
11033 axis = self._get_axis_number(axis)
11035 if freq is not None and fill_value is not lib.no_default:
11036 # GH#53832
11037 raise ValueError(
11038 "Passing a 'freq' together with a 'fill_value' is not allowed."
11039 )
11041 if is_list_like(periods) and isinstance(self, ABCSeries):
11042 return self.to_frame().shift(
11043 periods=periods,
11044 freq=freq,
11045 axis=axis,
11046 fill_value=fill_value,
11047 suffix=suffix,
11048 )
11049 elif suffix:
11050 raise ValueError("Cannot specify `suffix` if `periods` is an int.")
11051 periods = cast("int", periods)
11053 if periods == 0:
11054 return self.copy(deep=False)
11056 if freq is None:
11057 # when freq is None, data is shifted, index is not
11058 axis = self._get_axis_number(axis)
11059 assert axis == 0 # axis == 1 cases handled in DataFrame.shift
11060 new_data = self._mgr.shift(periods=periods, fill_value=fill_value)
11061 return self._constructor_from_mgr(
11062 new_data, axes=new_data.axes
11063 ).__finalize__(self, method="shift")
11065 return self._shift_with_freq(periods, axis, freq)
11067 @final
11068 def _shift_with_freq(self, periods: int, axis: int, freq) -> Self:
11069 # see shift.__doc__
11070 # when freq is given, index is shifted, data is not
11071 index = self._get_axis(axis)
11073 if freq == "infer":
11074 freq = getattr(index, "freq", None)
11076 if freq is None:
11077 freq = getattr(index, "_inferred_freq_str", None)
11079 if freq is None:
11080 msg = "Freq was not set in the index hence cannot be inferred"
11081 raise ValueError(msg)
11083 elif isinstance(freq, str):
11084 is_period = isinstance(index, PeriodIndex)
11085 freq = to_offset(freq, is_period=is_period)
11087 if isinstance(index, PeriodIndex):
11088 orig_freq = to_offset(index.freq)
11089 if freq != orig_freq:
11090 assert orig_freq is not None # for mypy
11091 raise ValueError(
11092 f"Given freq {PeriodDtype(freq)._freqstr} "
11093 f"does not match PeriodIndex freq "
11094 f"{PeriodDtype(orig_freq)._freqstr}"
11095 )
11096 new_ax: Index = index.shift(periods)
11097 else:
11098 new_ax = index.shift(periods, freq)
11100 result = self.set_axis(new_ax, axis=axis)
11101 return result.__finalize__(self, method="shift")
11103 @final
11104 def truncate(
11105 self,
11106 before=None,
11107 after=None,
11108 axis: Axis | None = None,
11109 copy: bool | lib.NoDefault = lib.no_default,
11110 ) -> Self:
11111 """
11112 Truncate a Series or DataFrame before and after some index value.
11114 This is a useful shorthand for boolean indexing based on index
11115 values above or below certain thresholds.
11117 Parameters
11118 ----------
11119 before : date, str, int
11120 Truncate all rows before this index value.
11121 after : date, str, int
11122 Truncate all rows after this index value.
11123 axis : {0 or 'index', 1 or 'columns'}, optional
11124 Axis to truncate. Truncates the index (rows) by default.
11125 For `Series` this parameter is unused and defaults to 0.
11126 copy : bool, default False
11127 This keyword is now ignored; changing its value will have no
11128 impact on the method.
11130 .. deprecated:: 3.0.0
11132 This keyword is ignored and will be removed in pandas 4.0. Since
11133 pandas 3.0, this method always returns a new object using a lazy
11134 copy mechanism that defers copies until necessary
11135 (Copy-on-Write). See the `user guide on Copy-on-Write
11136 <https://pandas.pydata.org/docs/dev/user_guide/migration.html>`__
11137 for more details.
11139 Returns
11140 -------
11141 type of caller
11142 The truncated Series or DataFrame.
11144 See Also
11145 --------
11146 DataFrame.loc : Select a subset of a DataFrame by label.
11147 DataFrame.iloc : Select a subset of a DataFrame by position.
11149 Notes
11150 -----
11151 If the index being truncated contains only datetime values,
11152 `before` and `after` may be specified as strings instead of
11153 Timestamps.
11155 Examples
11156 --------
11157 >>> df = pd.DataFrame(
11158 ... {
11159 ... "A": ["a", "b", "c", "d", "e"],
11160 ... "B": ["f", "g", "h", "i", "j"],
11161 ... "C": ["k", "l", "m", "n", "o"],
11162 ... },
11163 ... index=[1, 2, 3, 4, 5],
11164 ... )
11165 >>> df
11166 A B C
11167 1 a f k
11168 2 b g l
11169 3 c h m
11170 4 d i n
11171 5 e j o
11173 >>> df.truncate(before=2, after=4)
11174 A B C
11175 2 b g l
11176 3 c h m
11177 4 d i n
11179 The columns of a DataFrame can be truncated.
11181 >>> df.truncate(before="A", after="B", axis="columns")
11182 A B
11183 1 a f
11184 2 b g
11185 3 c h
11186 4 d i
11187 5 e j
11189 For Series, only rows can be truncated.
11191 >>> df["A"].truncate(before=2, after=4)
11192 2 b
11193 3 c
11194 4 d
11195 Name: A, dtype: str
11197 The index values in ``truncate`` can be datetimes or string
11198 dates.
11200 >>> dates = pd.date_range("2016-01-01", "2016-02-01", freq="s")
11201 >>> df = pd.DataFrame(index=dates, data={"A": 1})
11202 >>> df.tail()
11203 A
11204 2016-01-31 23:59:56 1
11205 2016-01-31 23:59:57 1
11206 2016-01-31 23:59:58 1
11207 2016-01-31 23:59:59 1
11208 2016-02-01 00:00:00 1
11210 >>> df.truncate(
11211 ... before=pd.Timestamp("2016-01-05"), after=pd.Timestamp("2016-01-10")
11212 ... ).tail()
11213 A
11214 2016-01-09 23:59:56 1
11215 2016-01-09 23:59:57 1
11216 2016-01-09 23:59:58 1
11217 2016-01-09 23:59:59 1
11218 2016-01-10 00:00:00 1
11220 Because the index is a DatetimeIndex containing only dates, we can
11221 specify `before` and `after` as strings. They will be coerced to
11222 Timestamps before truncation.
11224 >>> df.truncate("2016-01-05", "2016-01-10").tail()
11225 A
11226 2016-01-09 23:59:56 1
11227 2016-01-09 23:59:57 1
11228 2016-01-09 23:59:58 1
11229 2016-01-09 23:59:59 1
11230 2016-01-10 00:00:00 1
11232 Note that ``truncate`` assumes a 0 value for any unspecified time
11233 component (midnight). This differs from partial string slicing, which
11234 returns any partially matching dates.
11236 >>> df.loc["2016-01-05":"2016-01-10", :].tail()
11237 A
11238 2016-01-10 23:59:55 1
11239 2016-01-10 23:59:56 1
11240 2016-01-10 23:59:57 1
11241 2016-01-10 23:59:58 1
11242 2016-01-10 23:59:59 1
11243 """
11244 self._check_copy_deprecation(copy)
11246 if axis is None:
11247 axis = 0
11248 axis = self._get_axis_number(axis)
11249 ax = self._get_axis(axis)
11251 # GH 17935
11252 # Check that index is sorted
11253 if not ax.is_monotonic_increasing and not ax.is_monotonic_decreasing:
11254 raise ValueError("truncate requires a sorted index")
11256 # if we have a date index, convert to dates, otherwise
11257 # treat like a slice
11258 if ax._is_all_dates:
11259 from pandas.core.tools.datetimes import to_datetime
11261 if before is not None:
11262 # Avoid converting to NaT
11263 before = to_datetime(before)
11264 if after is not None:
11265 # Avoid converting to NaT
11266 after = to_datetime(after)
11268 if before is not None and after is not None and before > after:
11269 raise ValueError(f"Truncate: {after} must be after {before}")
11271 if len(ax) > 1 and ax.is_monotonic_decreasing and ax.nunique() > 1:
11272 before, after = after, before
11274 slicer = [slice(None, None)] * self._AXIS_LEN
11275 slicer[axis] = slice(before, after)
11276 result = self.loc[tuple(slicer)]
11278 if isinstance(ax, MultiIndex):
11279 setattr(result, self._get_axis_name(axis), ax.truncate(before, after))
11281 result = result.copy(deep=False)
11283 return result
11285 @final
11286 def tz_convert(
11287 self,
11288 tz,
11289 axis: Axis = 0,
11290 level=None,
11291 copy: bool | lib.NoDefault = lib.no_default,
11292 ) -> Self:
11293 """
11294 Convert tz-aware axis to target time zone.
11296 This method converts the timezone of a datetime-based index from one
11297 timezone to another.
11299 Parameters
11300 ----------
11301 tz : str or tzinfo object or None
11302 Target time zone. Passing ``None`` will convert to
11303 UTC and remove the timezone information.
11304 axis : {0 or 'index', 1 or 'columns'}, default 0
11305 The axis to convert
11306 level : int, str, default None
11307 If axis is a MultiIndex, convert a specific level. Otherwise
11308 must be None.
11309 copy : bool, default False
11310 This keyword is now ignored; changing its value will have no
11311 impact on the method.
11313 .. deprecated:: 3.0.0
11315 This keyword is ignored and will be removed in pandas 4.0. Since
11316 pandas 3.0, this method always returns a new object using a lazy
11317 copy mechanism that defers copies until necessary
11318 (Copy-on-Write). See the `user guide on Copy-on-Write
11319 <https://pandas.pydata.org/docs/dev/user_guide/migration.html>`__
11320 for more details.
11322 Returns
11323 -------
11324 Series/DataFrame
11325 Object with time zone converted axis.
11327 Raises
11328 ------
11329 TypeError
11330 If the axis is tz-naive.
11332 See Also
11333 --------
11334 DataFrame.tz_localize: Localize tz-naive index of DataFrame to target time zone.
11335 Series.tz_localize: Localize tz-naive index of Series to target time zone.
11337 Examples
11338 --------
11339 Change to another time zone:
11341 >>> s = pd.Series(
11342 ... [1],
11343 ... index=pd.DatetimeIndex(["2018-09-15 01:30:00+02:00"]),
11344 ... )
11345 >>> s.tz_convert("Asia/Shanghai")
11346 2018-09-15 07:30:00+08:00 1
11347 dtype: int64
11349 Pass None to convert to UTC and get a tz-naive index:
11351 >>> s = pd.Series([1], index=pd.DatetimeIndex(["2018-09-15 01:30:00+02:00"]))
11352 >>> s.tz_convert(None)
11353 2018-09-14 23:30:00 1
11354 dtype: int64
11355 """
11356 self._check_copy_deprecation(copy)
11357 axis = self._get_axis_number(axis)
11358 ax = self._get_axis(axis)
11360 def _tz_convert(ax, tz):
11361 if not hasattr(ax, "tz_convert"):
11362 if len(ax) > 0:
11363 ax_name = self._get_axis_name(axis)
11364 raise TypeError(
11365 f"{ax_name} is not a valid DatetimeIndex or PeriodIndex"
11366 )
11367 ax = DatetimeIndex([], tz=tz)
11368 else:
11369 ax = ax.tz_convert(tz)
11370 return ax
11372 # if a level is given it must be a MultiIndex level or
11373 # equivalent to the axis name
11374 if isinstance(ax, MultiIndex):
11375 level = ax._get_level_number(level)
11376 new_level = _tz_convert(ax.levels[level], tz)
11377 ax = ax.set_levels(new_level, level=level)
11378 else:
11379 if level not in (None, 0, ax.name):
11380 raise ValueError(f"The level {level} is not valid")
11381 ax = _tz_convert(ax, tz)
11383 result = self.copy(deep=False)
11384 result = result.set_axis(ax, axis=axis)
11385 return result.__finalize__(self, method="tz_convert")
11387 @final
11388 def tz_localize(
11389 self,
11390 tz,
11391 axis: Axis = 0,
11392 level=None,
11393 copy: bool | lib.NoDefault = lib.no_default,
11394 ambiguous: TimeAmbiguous = "raise",
11395 nonexistent: TimeNonexistent = "raise",
11396 ) -> Self:
11397 """
11398 Localize time zone naive index of a Series or DataFrame to target time zone.
11400 This operation localizes the Index. To localize the values in a
11401 time zone naive Series, use :meth:`Series.dt.tz_localize`.
11403 Parameters
11404 ----------
11405 tz : str or tzinfo or None
11406 Time zone to attach to the index; the wall time of each index
11407 label is preserved. Passing ``None`` detaches the time zone from
11408 a tz-aware index, returning a tz-naive index with the same wall
11409 time.
11410 axis : {0 or 'index', 1 or 'columns'}, default 0
11411 The axis to localize
11412 level : int, str, default None
11413 If axis is a MultiIndex, localize a specific level. Otherwise
11414 must be None.
11415 copy : bool, default False
11416 This keyword is now ignored; changing its value will have no
11417 impact on the method.
11419 .. deprecated:: 3.0.0
11421 This keyword is ignored and will be removed in pandas 4.0. Since
11422 pandas 3.0, this method always returns a new object using a lazy
11423 copy mechanism that defers copies until necessary
11424 (Copy-on-Write). See the `user guide on Copy-on-Write
11425 <https://pandas.pydata.org/docs/dev/user_guide/migration.html>`__
11426 for more details.
11428 ambiguous : 'infer', bool, bool-ndarray, 'NaT', default 'raise'
11429 When clocks moved backward due to DST, ambiguous times may arise.
11430 For example in Central European Time (UTC+01), when going from
11431 03:00 DST to 02:00 non-DST, 02:30:00 local time occurs both at
11432 00:30:00 UTC and at 01:30:00 UTC. In such a situation, the
11433 `ambiguous` parameter dictates how ambiguous times should be
11434 handled.
11436 - 'infer' will attempt to infer fall dst-transition hours based on
11437 order. Requires that the timestamps are monotonically increasing.
11438 - bool (or bool-ndarray) where True signifies a DST time, False designates
11439 a non-DST time (note that this flag is only applicable for
11440 ambiguous times)
11441 - 'NaT' will return NaT where there are ambiguous times
11442 - 'raise' will raise a ValueError if there are ambiguous
11443 times.
11444 nonexistent : str, default 'raise'
11445 A nonexistent time does not exist in a particular timezone
11446 where clocks moved forward due to DST. Valid values are:
11448 - 'shift_forward' will shift the nonexistent time forward to the
11449 closest existing time
11450 - 'shift_backward' will shift the nonexistent time backward to the
11451 closest existing time
11452 - 'NaT' will return NaT where there are nonexistent times
11453 - timedelta objects will shift nonexistent times by the timedelta
11454 - 'raise' will raise a ValueError if there are
11455 nonexistent times.
11457 Returns
11458 -------
11459 Series/DataFrame
11460 Same type as the input, with time zone naive or aware index, depending on
11461 ``tz``.
11463 Raises
11464 ------
11465 TypeError
11466 If the TimeSeries is tz-aware and tz is not None.
11468 See Also
11469 --------
11470 Series.dt.tz_localize: Localize the values in a time zone naive Series.
11471 Timestamp.tz_localize: Localize the Timestamp to a timezone.
11473 Examples
11474 --------
11475 Attach a time zone to tz-naive timestamps:
11477 >>> s = pd.Series(
11478 ... [1],
11479 ... index=pd.DatetimeIndex(["2018-09-15 01:30:00"]),
11480 ... )
11481 >>> s.tz_localize("CET")
11482 2018-09-15 01:30:00+02:00 1
11483 dtype: int64
11485 Pass None to detach the time zone from tz-aware timestamps:
11487 >>> s = pd.Series([1], index=pd.DatetimeIndex(["2018-09-15 01:30:00+02:00"]))
11488 >>> s.tz_localize(None)
11489 2018-09-15 01:30:00 1
11490 dtype: int64
11492 Be careful with DST changes. When there is sequential data, pandas
11493 can infer the DST time:
11495 >>> s = pd.Series(
11496 ... range(7),
11497 ... index=pd.DatetimeIndex(
11498 ... [
11499 ... "2018-10-28 01:30:00",
11500 ... "2018-10-28 02:00:00",
11501 ... "2018-10-28 02:30:00",
11502 ... "2018-10-28 02:00:00",
11503 ... "2018-10-28 02:30:00",
11504 ... "2018-10-28 03:00:00",
11505 ... "2018-10-28 03:30:00",
11506 ... ]
11507 ... ),
11508 ... )
11509 >>> s.tz_localize("CET", ambiguous="infer")
11510 2018-10-28 01:30:00+02:00 0
11511 2018-10-28 02:00:00+02:00 1
11512 2018-10-28 02:30:00+02:00 2
11513 2018-10-28 02:00:00+01:00 3
11514 2018-10-28 02:30:00+01:00 4
11515 2018-10-28 03:00:00+01:00 5
11516 2018-10-28 03:30:00+01:00 6
11517 dtype: int64
11519 In some cases, inferring the DST is impossible. In such cases, you can
11520 pass an ndarray to the ambiguous parameter to set the DST explicitly
11522 >>> s = pd.Series(
11523 ... range(3),
11524 ... index=pd.DatetimeIndex(
11525 ... [
11526 ... "2018-10-28 01:20:00",
11527 ... "2018-10-28 02:36:00",
11528 ... "2018-10-28 03:46:00",
11529 ... ]
11530 ... ),
11531 ... )
11532 >>> s.tz_localize("CET", ambiguous=np.array([True, True, False]))
11533 2018-10-28 01:20:00+02:00 0
11534 2018-10-28 02:36:00+02:00 1
11535 2018-10-28 03:46:00+01:00 2
11536 dtype: int64
11538 If the DST transition causes nonexistent times, you can shift these
11539 dates forward or backward with a timedelta object or `'shift_forward'`
11540 or `'shift_backward'`.
11542 >>> dti = pd.DatetimeIndex(
11543 ... ["2015-03-29 02:30:00", "2015-03-29 03:30:00"], dtype="M8[ns]"
11544 ... )
11545 >>> s = pd.Series(range(2), index=dti)
11546 >>> s.tz_localize("Europe/Warsaw", nonexistent="shift_forward")
11547 2015-03-29 03:00:00+02:00 0
11548 2015-03-29 03:30:00+02:00 1
11549 dtype: int64
11550 >>> s.tz_localize("Europe/Warsaw", nonexistent="shift_backward")
11551 2015-03-29 01:59:59.999999999+01:00 0
11552 2015-03-29 03:30:00.000000000+02:00 1
11553 dtype: int64
11554 >>> s.tz_localize("Europe/Warsaw", nonexistent=pd.Timedelta("1h"))
11555 2015-03-29 03:30:00+02:00 0
11556 2015-03-29 03:30:00+02:00 1
11557 dtype: int64
11558 """
11559 self._check_copy_deprecation(copy)
11560 nonexistent_options = ("raise", "NaT", "shift_forward", "shift_backward")
11561 if nonexistent not in nonexistent_options and not isinstance(
11562 nonexistent, dt.timedelta
11563 ):
11564 raise ValueError(
11565 "The nonexistent argument must be one of 'raise', "
11566 "'NaT', 'shift_forward', 'shift_backward' or "
11567 "a timedelta object"
11568 )
11570 axis = self._get_axis_number(axis)
11571 ax = self._get_axis(axis)
11573 def _tz_localize(ax, tz, ambiguous, nonexistent):
11574 if not hasattr(ax, "tz_localize"):
11575 if len(ax) > 0:
11576 ax_name = self._get_axis_name(axis)
11577 raise TypeError(
11578 f"{ax_name} is not a valid DatetimeIndex or PeriodIndex"
11579 )
11580 ax = DatetimeIndex([], tz=tz)
11581 else:
11582 ax = ax.tz_localize(tz, ambiguous=ambiguous, nonexistent=nonexistent)
11583 return ax
11585 # if a level is given it must be a MultiIndex level or
11586 # equivalent to the axis name
11587 if isinstance(ax, MultiIndex):
11588 level = ax._get_level_number(level)
11589 new_level = _tz_localize(ax.levels[level], tz, ambiguous, nonexistent)
11590 ax = ax.set_levels(new_level, level=level)
11591 else:
11592 if level not in (None, 0, ax.name):
11593 raise ValueError(f"The level {level} is not valid")
11594 ax = _tz_localize(ax, tz, ambiguous, nonexistent)
11596 result = self.copy(deep=False)
11597 result = result.set_axis(ax, axis=axis)
11598 return result.__finalize__(self, method="tz_localize")
11600 # ----------------------------------------------------------------------
11601 # Numeric Methods
11603 def describe(
11604 self,
11605 percentiles=None,
11606 include=None,
11607 exclude=None,
11608 ) -> Self:
11609 return describe_ndframe(
11610 obj=self,
11611 include=include,
11612 exclude=exclude,
11613 percentiles=percentiles,
11614 ).__finalize__(self, method="describe")
11616 @final
11617 def pct_change(
11618 self,
11619 periods: int = 1,
11620 fill_method: None = None,
11621 freq=None,
11622 **kwargs,
11623 ) -> Self:
11624 """
11625 Fractional change between the current and a prior element.
11627 Computes the fractional change from the immediately previous row by
11628 default. This is useful in comparing the fraction of change in a time
11629 series of elements.
11631 .. note::
11633 Despite the name of this method, it calculates fractional change
11634 (also known as per unit change or relative change) and not
11635 percentage change. If you need the percentage change, multiply
11636 these values by 100.
11638 Parameters
11639 ----------
11640 periods : int, default 1
11641 Periods to shift for forming percent change.
11642 fill_method : None
11643 Must be None. This argument will be removed in a future version of pandas.
11644 freq : DateOffset, timedelta, or str, optional
11645 Increment to use from time series API (e.g. 'ME' or BDay()).
11646 **kwargs
11647 Additional keyword arguments are passed into
11648 `DataFrame.shift` or `Series.shift`.
11650 Returns
11651 -------
11652 Series or DataFrame
11653 The same type as the calling object.
11655 See Also
11656 --------
11657 Series.diff : Compute the difference of two elements in a Series.
11658 DataFrame.diff : Compute the difference of two elements in a DataFrame.
11659 Series.shift : Shift the index by some number of periods.
11660 DataFrame.shift : Shift the index by some number of periods.
11662 Examples
11663 --------
11664 **Series**
11666 >>> s = pd.Series([90, 91, 85])
11667 >>> s
11668 0 90
11669 1 91
11670 2 85
11671 dtype: int64
11673 >>> s.pct_change()
11674 0 NaN
11675 1 0.011111
11676 2 -0.065934
11677 dtype: float64
11679 >>> s.pct_change(periods=2)
11680 0 NaN
11681 1 NaN
11682 2 -0.055556
11683 dtype: float64
11685 See the percentage change in a Series where filling NAs with last
11686 valid observation forward to next valid.
11688 >>> s = pd.Series([90, 91, None, 85])
11689 >>> s
11690 0 90.0
11691 1 91.0
11692 2 NaN
11693 3 85.0
11694 dtype: float64
11696 >>> s.ffill().pct_change()
11697 0 NaN
11698 1 0.011111
11699 2 0.000000
11700 3 -0.065934
11701 dtype: float64
11703 **DataFrame**
11705 Percentage change in French franc, Deutsche Mark, and Italian lira from
11706 1980-01-01 to 1980-03-01.
11708 >>> df = pd.DataFrame(
11709 ... {
11710 ... "FR": [4.0405, 4.0963, 4.3149],
11711 ... "GR": [1.7246, 1.7482, 1.8519],
11712 ... "IT": [804.74, 810.01, 860.13],
11713 ... },
11714 ... index=["1980-01-01", "1980-02-01", "1980-03-01"],
11715 ... )
11716 >>> df
11717 FR GR IT
11718 1980-01-01 4.0405 1.7246 804.74
11719 1980-02-01 4.0963 1.7482 810.01
11720 1980-03-01 4.3149 1.8519 860.13
11722 >>> df.pct_change()
11723 FR GR IT
11724 1980-01-01 NaN NaN NaN
11725 1980-02-01 0.013810 0.013684 0.006549
11726 1980-03-01 0.053365 0.059318 0.061876
11728 Percentage of change in GOOG and APPL stock volume. Shows computing
11729 the percentage change between columns.
11731 >>> df = pd.DataFrame(
11732 ... {
11733 ... "2016": [1769950, 30586265],
11734 ... "2015": [1500923, 40912316],
11735 ... "2014": [1371819, 41403351],
11736 ... },
11737 ... index=["GOOG", "APPL"],
11738 ... )
11739 >>> df
11740 2016 2015 2014
11741 GOOG 1769950 1500923 1371819
11742 APPL 30586265 40912316 41403351
11744 >>> df.pct_change(axis="columns", periods=-1)
11745 2016 2015 2014
11746 GOOG 0.179241 0.094112 NaN
11747 APPL -0.252395 -0.011860 NaN
11748 """
11749 # GH#53491
11750 if fill_method is not None:
11751 raise ValueError(f"fill_method must be None; got {fill_method=}.")
11753 axis = self._get_axis_number(kwargs.pop("axis", "index"))
11754 shifted = self.shift(periods=periods, freq=freq, axis=axis, **kwargs)
11755 # Unsupported left operand type for / ("Self")
11756 rs = self / shifted - 1 # type: ignore[operator]
11757 if freq is not None:
11758 # Shift method is implemented differently when freq is not None
11759 # We want to restore the original index
11760 rs = rs.loc[~rs.index.duplicated()]
11761 rs = rs.reindex_like(self)
11762 return rs.__finalize__(self, method="pct_change") # type: ignore[return-value]
11764 @final
11765 def _logical_func(
11766 self,
11767 name: str,
11768 func,
11769 axis: Axis | None = 0,
11770 bool_only: bool = False,
11771 skipna: bool = True,
11772 **kwargs,
11773 ) -> Series | bool:
11774 nv.validate_logical_func((), kwargs, fname=name)
11775 validate_bool_kwarg(skipna, "skipna", none_allowed=False)
11777 if self.ndim > 1 and axis is None:
11778 # Reduce along one dimension then the other, to simplify DataFrame._reduce
11779 res = self._logical_func(
11780 name, func, axis=0, bool_only=bool_only, skipna=skipna, **kwargs
11781 )
11782 # error: Item "bool" of "Series | bool" has no attribute "_logical_func"
11783 return res._logical_func( # type: ignore[union-attr]
11784 name, func, skipna=skipna, **kwargs
11785 )
11786 elif axis is None:
11787 axis = 0
11789 if (
11790 self.ndim > 1
11791 and axis == 1
11792 and len(self._mgr.blocks) > 1
11793 # TODO(EA2D): special-case not needed
11794 and all(block.values.ndim == 2 for block in self._mgr.blocks)
11795 and not kwargs
11796 ):
11797 # Fastpath avoiding potentially expensive transpose
11798 obj = self
11799 if bool_only:
11800 obj = self._get_bool_data()
11801 return obj._reduce_axis1(name, func, skipna=skipna)
11803 return self._reduce(
11804 func,
11805 name=name,
11806 axis=axis,
11807 skipna=skipna,
11808 numeric_only=bool_only,
11809 filter_type="bool",
11810 )
11812 def any(
11813 self,
11814 *,
11815 axis: Axis | None = 0,
11816 bool_only: bool = False,
11817 skipna: bool = True,
11818 **kwargs,
11819 ) -> Series | bool:
11820 return self._logical_func(
11821 "any", nanops.nanany, axis, bool_only, skipna, **kwargs
11822 )
11824 def all(
11825 self,
11826 *,
11827 axis: Axis = 0,
11828 bool_only: bool = False,
11829 skipna: bool = True,
11830 **kwargs,
11831 ) -> Series | bool:
11832 return self._logical_func(
11833 "all", nanops.nanall, axis, bool_only, skipna, **kwargs
11834 )
11836 @final
11837 def _accum_func(
11838 self,
11839 name: str,
11840 func,
11841 axis: Axis | None = None,
11842 skipna: bool = True,
11843 *args,
11844 **kwargs,
11845 ):
11846 skipna = nv.validate_cum_func_with_skipna(skipna, args, kwargs, name)
11847 if axis is None:
11848 axis = 0
11849 else:
11850 axis = self._get_axis_number(axis)
11852 if axis == 1:
11853 return self.T._accum_func(
11854 name,
11855 func,
11856 axis=0,
11857 skipna=skipna,
11858 *args, # noqa: B026
11859 **kwargs,
11860 ).T
11862 def block_accum_func(blk_values):
11863 values = blk_values.T if hasattr(blk_values, "T") else blk_values
11865 result: np.ndarray | ExtensionArray
11866 if isinstance(values, ExtensionArray):
11867 result = values._accumulate(name, skipna=skipna, **kwargs)
11868 else:
11869 result = nanops.na_accum_func(values, func, skipna=skipna)
11871 result = result.T if hasattr(result, "T") else result
11872 return result
11874 result = self._mgr.apply(block_accum_func)
11876 return self._constructor_from_mgr(result, axes=result.axes).__finalize__(
11877 self, method=name
11878 )
11880 def cummax(self, axis: Axis = 0, skipna: bool = True, *args, **kwargs) -> Self:
11881 return self._accum_func(
11882 "cummax", np.maximum.accumulate, axis, skipna, *args, **kwargs
11883 )
11885 def cummin(self, axis: Axis = 0, skipna: bool = True, *args, **kwargs) -> Self:
11886 return self._accum_func(
11887 "cummin", np.minimum.accumulate, axis, skipna, *args, **kwargs
11888 )
11890 def cumsum(self, axis: Axis = 0, skipna: bool = True, *args, **kwargs) -> Self:
11891 return self._accum_func("cumsum", np.cumsum, axis, skipna, *args, **kwargs)
11893 def cumprod(self, axis: Axis = 0, skipna: bool = True, *args, **kwargs) -> Self:
11894 return self._accum_func("cumprod", np.cumprod, axis, skipna, *args, **kwargs)
11896 @final
11897 def _stat_function_ddof(
11898 self,
11899 name: str,
11900 func,
11901 axis: Axis | None = 0,
11902 skipna: bool = True,
11903 ddof: int = 1,
11904 numeric_only: bool = False,
11905 **kwargs,
11906 ) -> Series | float:
11907 nv.validate_stat_ddof_func((), kwargs, fname=name)
11908 validate_bool_kwarg(skipna, "skipna", none_allowed=False)
11909 if not is_bool(numeric_only):
11910 warnings.warn(
11911 "Passing non-boolean values for 'numeric_only' is deprecated and "
11912 "will raise in a future version of pandas.",
11913 Pandas4Warning,
11914 stacklevel=find_stack_level(),
11915 )
11917 return self._reduce(
11918 func, name, axis=axis, numeric_only=numeric_only, skipna=skipna, ddof=ddof
11919 )
11921 def sem(
11922 self,
11923 *,
11924 axis: Axis | None = 0,
11925 skipna: bool = True,
11926 ddof: int = 1,
11927 numeric_only: bool = False,
11928 **kwargs,
11929 ) -> Series | float:
11930 return self._stat_function_ddof(
11931 "sem", nanops.nansem, axis, skipna, ddof, numeric_only, **kwargs
11932 )
11934 def var(
11935 self,
11936 *,
11937 axis: Axis | None = 0,
11938 skipna: bool = True,
11939 ddof: int = 1,
11940 numeric_only: bool = False,
11941 **kwargs,
11942 ) -> Series | float:
11943 return self._stat_function_ddof(
11944 "var", nanops.nanvar, axis, skipna, ddof, numeric_only, **kwargs
11945 )
11947 def std(
11948 self,
11949 *,
11950 axis: Axis | None = 0,
11951 skipna: bool = True,
11952 ddof: int = 1,
11953 numeric_only: bool = False,
11954 **kwargs,
11955 ) -> Series | float:
11956 return self._stat_function_ddof(
11957 "std", nanops.nanstd, axis, skipna, ddof, numeric_only, **kwargs
11958 )
11960 @final
11961 def _stat_function(
11962 self,
11963 name: str,
11964 func,
11965 axis: Axis | None = 0,
11966 skipna: bool = True,
11967 numeric_only: bool = False,
11968 **kwargs,
11969 ):
11970 assert name in ["median", "mean", "min", "max", "kurt", "skew"], name
11971 nv.validate_func(name, (), kwargs)
11973 validate_bool_kwarg(skipna, "skipna", none_allowed=False)
11974 if not is_bool(numeric_only):
11975 warnings.warn(
11976 "Passing non-boolean values for 'numeric_only' is deprecated and "
11977 "will raise in a future version of pandas.",
11978 Pandas4Warning,
11979 stacklevel=find_stack_level(),
11980 )
11982 return self._reduce(
11983 func, name=name, axis=axis, skipna=skipna, numeric_only=numeric_only
11984 )
11986 def min(
11987 self,
11988 *,
11989 axis: Axis | None = 0,
11990 skipna: bool = True,
11991 numeric_only: bool = False,
11992 **kwargs,
11993 ):
11994 return self._stat_function(
11995 "min",
11996 nanops.nanmin,
11997 axis,
11998 skipna,
11999 numeric_only,
12000 **kwargs,
12001 )
12003 def max(
12004 self,
12005 *,
12006 axis: Axis | None = 0,
12007 skipna: bool = True,
12008 numeric_only: bool = False,
12009 **kwargs,
12010 ):
12011 return self._stat_function(
12012 "max",
12013 nanops.nanmax,
12014 axis,
12015 skipna,
12016 numeric_only,
12017 **kwargs,
12018 )
12020 def mean(
12021 self,
12022 *,
12023 axis: Axis | None = 0,
12024 skipna: bool = True,
12025 numeric_only: bool = False,
12026 **kwargs,
12027 ) -> Series | float:
12028 return self._stat_function(
12029 "mean", nanops.nanmean, axis, skipna, numeric_only, **kwargs
12030 )
12032 def median(
12033 self,
12034 *,
12035 axis: Axis | None = 0,
12036 skipna: bool = True,
12037 numeric_only: bool = False,
12038 **kwargs,
12039 ) -> Series | float:
12040 return self._stat_function(
12041 "median", nanops.nanmedian, axis, skipna, numeric_only, **kwargs
12042 )
12044 def skew(
12045 self,
12046 *,
12047 axis: Axis | None = 0,
12048 skipna: bool = True,
12049 numeric_only: bool = False,
12050 **kwargs,
12051 ) -> Series | float:
12052 return self._stat_function(
12053 "skew", nanops.nanskew, axis, skipna, numeric_only, **kwargs
12054 )
12056 def kurt(
12057 self,
12058 *,
12059 axis: Axis | None = 0,
12060 skipna: bool = True,
12061 numeric_only: bool = False,
12062 **kwargs,
12063 ) -> Series | float:
12064 return self._stat_function(
12065 "kurt", nanops.nankurt, axis, skipna, numeric_only, **kwargs
12066 )
12068 kurtosis = kurt
12070 @final
12071 def _min_count_stat_function(
12072 self,
12073 name: str,
12074 func,
12075 axis: Axis | None = 0,
12076 skipna: bool = True,
12077 numeric_only: bool = False,
12078 min_count: int = 0,
12079 **kwargs,
12080 ):
12081 assert name in ["sum", "prod"], name
12082 nv.validate_func(name, (), kwargs)
12084 validate_bool_kwarg(skipna, "skipna", none_allowed=False)
12085 if not is_bool(numeric_only):
12086 warnings.warn(
12087 "Passing non-boolean values for 'numeric_only' is deprecated and "
12088 "will raise in a future version of pandas.",
12089 Pandas4Warning,
12090 stacklevel=find_stack_level(),
12091 )
12093 return self._reduce(
12094 func,
12095 name=name,
12096 axis=axis,
12097 skipna=skipna,
12098 numeric_only=numeric_only,
12099 min_count=min_count,
12100 )
12102 def sum(
12103 self,
12104 *,
12105 axis: Axis | None = 0,
12106 skipna: bool = True,
12107 numeric_only: bool = False,
12108 min_count: int = 0,
12109 **kwargs,
12110 ):
12111 return self._min_count_stat_function(
12112 "sum", nanops.nansum, axis, skipna, numeric_only, min_count, **kwargs
12113 )
12115 def prod(
12116 self,
12117 *,
12118 axis: Axis | None = 0,
12119 skipna: bool = True,
12120 numeric_only: bool = False,
12121 min_count: int = 0,
12122 **kwargs,
12123 ):
12124 return self._min_count_stat_function(
12125 "prod",
12126 nanops.nanprod,
12127 axis,
12128 skipna,
12129 numeric_only,
12130 min_count,
12131 **kwargs,
12132 )
12134 product = prod
12136 @final
12137 def rolling(
12138 self,
12139 window: int | dt.timedelta | str | BaseOffset | BaseIndexer,
12140 min_periods: int | None = None,
12141 center: bool = False,
12142 win_type: str | None = None,
12143 on: str | None = None,
12144 closed: IntervalClosedType | None = None,
12145 step: int | None = None,
12146 method: str = "single",
12147 ) -> Window | Rolling:
12148 """
12149 Provide rolling window calculations.
12151 This method returns a rolling window object, enabling aggregation,
12152 transformation, and other operations over a sliding window of a
12153 specified size.
12155 Parameters
12156 ----------
12157 window : int, timedelta, str, offset, or BaseIndexer subclass
12158 Interval of the moving window.
12160 If an integer, the delta between the start and end of each window.
12161 The number of points in the window depends on the ``closed`` argument.
12163 If a timedelta, str, or offset, the time period of each window. Each
12164 window will be a variable sized based on the observations included in
12165 the time-period. This is only valid for datetimelike indexes.
12166 The offset must correspond to a fixed frequency (for example, ``'2D'``
12167 or ``'1h'``); non-fixed frequencies such as ``'B'`` (business day) or
12168 ``'ME'`` (month end) are not supported and raise ``ValueError``.
12169 To learn more about the offsets & frequency strings, please see
12170 :ref:`this link<timeseries.offset_aliases>`.
12172 If a BaseIndexer subclass, the window boundaries
12173 based on the defined ``get_window_bounds`` method. Additional rolling
12174 keyword arguments, namely ``min_periods``, ``center``, ``closed`` and
12175 ``step`` will be passed to ``get_window_bounds``.
12177 min_periods : int, default None
12178 Minimum number of observations in window required to have a value;
12179 otherwise, result is ``np.nan``.
12181 For a window that is specified by an offset, ``min_periods`` will default
12182 to 1.
12184 For a window that is specified by an integer, ``min_periods`` will default
12185 to the size of the window.
12187 center : bool, default False
12188 If False, set the window labels as the right edge of the window index.
12190 If True, set the window labels as the center of the window index.
12192 win_type : str, default None
12193 If ``None``, all points are evenly weighted.
12195 If a string, it must be a valid `scipy.signal window function
12196 <https://docs.scipy.org/doc/scipy/reference/signal.windows.html#module-scipy.signal.windows>`__.
12198 Certain Scipy window types require additional parameters to be passed
12199 in the aggregation function. The additional parameters must match
12200 the keywords specified in the Scipy window type method signature.
12202 on : str, optional
12203 For a DataFrame, a column label or Index level on which
12204 to calculate the rolling window, rather than the DataFrame's index.
12206 For integer ``window`` values, the window bounds are based on the number
12207 of observations and are not calculated using the values of the
12208 ``on`` column. The ``on`` column is excluded from the aggregation,
12209 but is included in the result when its values differ from the
12210 object's index.
12212 When ``on`` is specified, the values of that column also become the
12213 index of the :class:`Series` passed to :meth:`Rolling.apply` when
12214 ``raw=False``, in place of the original :class:`DataFrame` index.
12216 closed : str, default None
12217 Determines the inclusivity of points in the window
12219 If ``'right'``, uses the window (first, last] meaning the last point
12220 is included in the calculations.
12222 If ``'left'``, uses the window [first, last) meaning the first point
12223 is included in the calculations.
12225 If ``'both'``, uses the window [first, last] meaning all points in
12226 the window are included in the calculations.
12228 If ``'neither'``, uses the window (first, last) meaning the first
12229 and last points in the window are excluded from calculations.
12231 () and [] are referencing open and closed set
12232 notation respetively.
12234 Default ``None`` (``'right'``).
12236 step : int, default None
12237 Evaluate the window at every ``step`` result, equivalent to slicing as
12238 ``[::step]``. ``window`` must be an integer. Using a step argument other
12239 than None or 1 will produce a result with a different shape than the input.
12241 method : str {'single', 'table'}, default 'single'
12243 Execute the rolling operation per single column or row (``'single'``)
12244 or over the entire object (``'table'``).
12246 This argument is only implemented when specifying ``engine='numba'``
12247 in the method call.
12249 Returns
12250 -------
12251 pandas.api.typing.Window or pandas.api.typing.Rolling
12252 An instance of Window is returned if ``win_type`` is passed. Otherwise,
12253 an instance of Rolling is returned.
12255 See Also
12256 --------
12257 expanding : Provides expanding transformations.
12258 ewm : Provides exponential weighted functions.
12260 Notes
12261 -----
12262 See :ref:`Windowing Operations <window.generic>` for further usage details
12263 and examples.
12265 Examples
12266 --------
12267 >>> df = pd.DataFrame({"B": [0, 1, 2, np.nan, 4]})
12268 >>> df
12269 B
12270 0 0.0
12271 1 1.0
12272 2 2.0
12273 3 NaN
12274 4 4.0
12276 **window**
12278 Rolling sum with a window length of 2 observations.
12280 >>> df.rolling(2).sum()
12281 B
12282 0 NaN
12283 1 1.0
12284 2 3.0
12285 3 NaN
12286 4 NaN
12288 Rolling sum with a window span of 2 seconds.
12290 >>> df_time = pd.DataFrame(
12291 ... {"B": [0, 1, 2, np.nan, 4]},
12292 ... index=[
12293 ... pd.Timestamp("20130101 09:00:00"),
12294 ... pd.Timestamp("20130101 09:00:02"),
12295 ... pd.Timestamp("20130101 09:00:03"),
12296 ... pd.Timestamp("20130101 09:00:05"),
12297 ... pd.Timestamp("20130101 09:00:06"),
12298 ... ],
12299 ... )
12301 >>> df_time
12302 B
12303 2013-01-01 09:00:00 0.0
12304 2013-01-01 09:00:02 1.0
12305 2013-01-01 09:00:03 2.0
12306 2013-01-01 09:00:05 NaN
12307 2013-01-01 09:00:06 4.0
12309 >>> df_time.rolling("2s").sum()
12310 B
12311 2013-01-01 09:00:00 0.0
12312 2013-01-01 09:00:02 1.0
12313 2013-01-01 09:00:03 3.0
12314 2013-01-01 09:00:05 NaN
12315 2013-01-01 09:00:06 4.0
12317 Rolling sum with forward-looking windows with 3 seconds.
12319 >>> df_time.iloc[::-1].rolling("3s").sum().iloc[::-1]
12320 B
12321 2013-01-01 09:00:00 1.0
12322 2013-01-01 09:00:02 3.0
12323 2013-01-01 09:00:03 2.0
12324 2013-01-01 09:00:05 4.0
12325 2013-01-01 09:00:06 4.0
12327 .. note::
12329 Negative offset strings (e.g., ``"-5h"``) do not create forward-looking
12330 windows and should be avoided. They collapse to single-element windows.
12332 Rolling sum with forward looking windows with 2 observations.
12334 >>> indexer = pd.api.indexers.FixedForwardWindowIndexer(window_size=2)
12335 >>> df.rolling(window=indexer, min_periods=1).sum()
12336 B
12337 0 1.0
12338 1 3.0
12339 2 2.0
12340 3 4.0
12341 4 4.0
12343 **min_periods**
12345 Rolling sum with a window length of 2 observations, but only needs a minimum
12346 of 1 observation to calculate a value.
12348 >>> df.rolling(2, min_periods=1).sum()
12349 B
12350 0 0.0
12351 1 1.0
12352 2 3.0
12353 3 2.0
12354 4 4.0
12356 **center**
12358 Rolling sum with the result assigned to the center of the window index.
12360 >>> df.rolling(3, min_periods=1, center=True).sum()
12361 B
12362 0 1.0
12363 1 3.0
12364 2 3.0
12365 3 6.0
12366 4 4.0
12368 >>> df.rolling(3, min_periods=1, center=False).sum()
12369 B
12370 0 0.0
12371 1 1.0
12372 2 3.0
12373 3 3.0
12374 4 6.0
12376 **step**
12378 Rolling sum with a window length of 2 observations, minimum of 1 observation to
12379 calculate a value, and a step of 2.
12381 >>> df.rolling(2, min_periods=1, step=2).sum()
12382 B
12383 0 0.0
12384 2 3.0
12385 4 4.0
12387 **win_type**
12389 Rolling sum with a window length of 2, using the Scipy ``'gaussian'``
12390 window type. ``std`` is required in the aggregation function.
12392 >>> df.rolling(2, win_type="gaussian").sum(std=3)
12393 B
12394 0 NaN
12395 1 0.986207
12396 2 2.958621
12397 3 NaN
12398 4 NaN
12400 **on**
12402 Rolling sum with a window length of 2 days.
12404 >>> df = pd.DataFrame(
12405 ... {
12406 ... "A": [
12407 ... pd.to_datetime("2020-01-01"),
12408 ... pd.to_datetime("2020-01-01"),
12409 ... pd.to_datetime("2020-01-02"),
12410 ... ],
12411 ... "B": [1, 2, 3],
12412 ... },
12413 ... index=pd.date_range("2020", periods=3),
12414 ... )
12416 >>> df
12417 A B
12418 2020-01-01 2020-01-01 1
12419 2020-01-02 2020-01-01 2
12420 2020-01-03 2020-01-02 3
12422 >>> df.rolling("2D", on="A").sum()
12423 A B
12424 2020-01-01 2020-01-01 1.0
12425 2020-01-02 2020-01-01 3.0
12426 2020-01-03 2020-01-02 6.0
12427 """
12428 if win_type is not None:
12429 return Window(
12430 self,
12431 window=window,
12432 min_periods=min_periods,
12433 center=center,
12434 win_type=win_type,
12435 on=on,
12436 closed=closed,
12437 step=step,
12438 method=method,
12439 )
12441 return Rolling(
12442 self,
12443 window=window,
12444 min_periods=min_periods,
12445 center=center,
12446 win_type=win_type,
12447 on=on,
12448 closed=closed,
12449 step=step,
12450 method=method,
12451 )
12453 @final
12454 def expanding(
12455 self,
12456 min_periods: int = 1,
12457 method: Literal["single", "table"] = "single",
12458 ) -> Expanding:
12459 """
12460 Provide expanding window calculations.
12462 An expanding window yields the value of an aggregation statistic with all
12463 the data available up to that point in time.
12465 Parameters
12466 ----------
12467 min_periods : int, default 1
12468 Minimum number of observations in window required to have a value;
12469 otherwise, result is ``np.nan``.
12471 method : str {'single', 'table'}, default 'single'
12472 Execute the rolling operation per single column or row (``'single'``)
12473 or over the entire object (``'table'``).
12475 This argument is only implemented when specifying ``engine='numba'``
12476 in the method call.
12478 Returns
12479 -------
12480 pandas.api.typing.Expanding
12481 An instance of Expanding for further expanding window calculations,
12482 e.g. using the ``sum`` method.
12484 See Also
12485 --------
12486 rolling : Provides rolling window calculations.
12487 ewm : Provides exponential weighted functions.
12489 Notes
12490 -----
12491 See :ref:`Windowing Operations <window.expanding>` for further usage details
12492 and examples.
12494 Examples
12495 --------
12496 >>> df = pd.DataFrame({"B": [0, 1, 2, np.nan, 4]})
12497 >>> df
12498 B
12499 0 0.0
12500 1 1.0
12501 2 2.0
12502 3 NaN
12503 4 4.0
12505 **min_periods**
12507 Expanding sum with 1 vs 3 observations needed to calculate a value.
12509 >>> df.expanding(1).sum()
12510 B
12511 0 0.0
12512 1 1.0
12513 2 3.0
12514 3 3.0
12515 4 7.0
12516 >>> df.expanding(3).sum()
12517 B
12518 0 NaN
12519 1 NaN
12520 2 3.0
12521 3 3.0
12522 4 7.0
12523 """
12524 return Expanding(self, min_periods=min_periods, method=method)
12526 @final
12527 def ewm(
12528 self,
12529 com: float | None = None,
12530 span: float | None = None,
12531 halflife: float | TimedeltaConvertibleTypes | None = None,
12532 alpha: float | None = None,
12533 min_periods: int | None = 0,
12534 adjust: bool = True,
12535 ignore_na: bool = False,
12536 times: np.ndarray | DataFrame | Series | None = None,
12537 method: Literal["single", "table"] = "single",
12538 ) -> ExponentialMovingWindow:
12539 r"""
12540 Provide exponentially weighted (EW) calculations.
12542 Exactly one of ``com``, ``span``, ``halflife``, or ``alpha`` must be
12543 provided if ``times`` is not provided. If ``times`` is provided and
12544 ``adjust=True``, ``halflife`` and one of ``com``, ``span`` or ``alpha``
12545 may be provided.
12546 If ``times`` is provided and ``adjust=False``, ``halflife``
12547 must be the only provided decay-specification parameter.
12549 Parameters
12550 ----------
12551 com : float, optional
12552 Specify decay in terms of center of mass
12554 :math:`\alpha = 1 / (1 + com)`, for :math:`com \geq 0`.
12556 span : float, optional
12557 Specify decay in terms of span
12559 :math:`\alpha = 2 / (span + 1)`, for :math:`span \geq 1`.
12561 halflife : float, str, timedelta, optional
12562 Specify decay in terms of half-life
12564 :math:`\alpha = 1 - \exp\left(-\ln(2) / halflife\right)`,
12565 for :math:`halflife > 0`.
12567 If ``times`` is specified, a timedelta convertible unit over which an
12568 observation decays to half its value. Only applicable to ``mean()``,
12569 and halflife value will not apply to the other functions.
12571 alpha : float, optional
12572 Specify smoothing factor :math:`\alpha` directly
12574 :math:`0 < \alpha \leq 1`.
12576 min_periods : int, default 0
12577 Minimum number of observations in window required to have a value;
12578 otherwise, result is ``np.nan``.
12580 adjust : bool, default True
12581 Divide by decaying adjustment factor in beginning periods to account
12582 for imbalance in relative weightings (viewing EWMA as a moving average).
12584 - When ``adjust=True`` (default), the EW function is calculated
12585 using weights
12586 :math:`w_i = (1 - \alpha)^i`. For example, the EW moving
12587 average of the series [:math:`x_0, x_1, ..., x_t`] would be:
12589 .. math::
12590 y_t = \frac{x_t + (1 - \alpha)x_{t-1} + (1 - \alpha)^2 x_{t-2} + ... +
12591 (1 - \alpha)^t x_0}{1 + (1 - \alpha) + (1 - \alpha)^2 + ... +
12592 (1 - \alpha)^t}
12594 - When ``adjust=False``, the exponentially weighted function is calculated
12595 recursively:
12597 .. math::
12598 \begin{split}
12599 y_0 &= x_0\\
12600 y_t &= (1 - \alpha) y_{t-1} + \alpha x_t,
12601 \end{split}
12603 ignore_na : bool, default False
12604 Ignore missing values when calculating weights.
12606 - When ``ignore_na=False`` (default), weights are based on absolute
12607 positions.
12608 For example, the weights of :math:`x_0` and :math:`x_2`
12609 used in calculating the final weighted average of
12610 [:math:`x_0`, None, :math:`x_2`] are
12611 :math:`(1-\alpha)^2` and :math:`1` if ``adjust=True``, and
12612 :math:`(1-\alpha)^2` and :math:`\alpha` if ``adjust=False``.
12614 - When ``ignore_na=True``, weights are based
12615 on relative positions. For example, the weights of :math:`x_0` and
12616 :math:`x_2` used in calculating the final weighted average of
12617 [:math:`x_0`, None, :math:`x_2`] are :math:`1-\alpha` and :math:`1` if
12618 ``adjust=True``, and :math:`1-\alpha` and :math:`\alpha`
12619 if ``adjust=False``.
12621 times : np.ndarray, Series, default None
12623 Only applicable to ``mean()``.
12625 Times corresponding to the observations. Must be monotonically
12626 increasing and ``datetime64[ns]`` dtype.
12628 If 1-D array like, a sequence with the same shape as the observations.
12630 method : str {'single', 'table'}, default 'single'
12631 Execute the rolling operation per single column or row (``'single'``)
12632 or over the entire object (``'table'``).
12634 This argument is only implemented when specifying ``engine='numba'``
12635 in the method call.
12637 Only applicable to ``mean()``
12639 Returns
12640 -------
12641 pandas.api.typing.ExponentialMovingWindow
12642 An instance of ExponentialMovingWindow for further exponentially weighted
12643 (EW) calculations, e.g. using the ``mean`` method.
12645 See Also
12646 --------
12647 rolling : Provides rolling window calculations.
12648 expanding : Provides expanding transformations.
12650 Notes
12651 -----
12652 See :ref:`Windowing Operations <window.exponentially_weighted>`
12653 for further usage details and examples.
12655 Examples
12656 --------
12657 >>> df = pd.DataFrame({'B': [0, 1, 2, np.nan, 4]})
12658 >>> df
12659 B
12660 0 0.0
12661 1 1.0
12662 2 2.0
12663 3 NaN
12664 4 4.0
12666 >>> df.ewm(com=0.5).mean()
12667 B
12668 0 0.000000
12669 1 0.750000
12670 2 1.615385
12671 3 1.615385
12672 4 3.670213
12673 >>> df.ewm(alpha=2 / 3).mean()
12674 B
12675 0 0.000000
12676 1 0.750000
12677 2 1.615385
12678 3 1.615385
12679 4 3.670213
12681 **adjust**
12683 >>> df.ewm(com=0.5, adjust=True).mean()
12684 B
12685 0 0.000000
12686 1 0.750000
12687 2 1.615385
12688 3 1.615385
12689 4 3.670213
12690 >>> df.ewm(com=0.5, adjust=False).mean()
12691 B
12692 0 0.000000
12693 1 0.666667
12694 2 1.555556
12695 3 1.555556
12696 4 3.650794
12698 **ignore_na**
12700 >>> df.ewm(com=0.5, ignore_na=True).mean()
12701 B
12702 0 0.000000
12703 1 0.750000
12704 2 1.615385
12705 3 1.615385
12706 4 3.225000
12707 >>> df.ewm(com=0.5, ignore_na=False).mean()
12708 B
12709 0 0.000000
12710 1 0.750000
12711 2 1.615385
12712 3 1.615385
12713 4 3.670213
12715 **times**
12717 Exponentially weighted mean with weights calculated with a
12718 timedelta ``halflife`` relative to ``times``.
12720 >>> times = ['2020-01-01', '2020-01-03', '2020-01-10', '2020-01-15',
12721 ... '2020-01-17']
12722 >>> df.ewm(halflife='4 days', times=pd.DatetimeIndex(times)).mean()
12723 B
12724 0 0.000000
12725 1 0.585786
12726 2 1.523889
12727 3 1.523889
12728 4 3.233686
12729 """
12730 return ExponentialMovingWindow(
12731 self,
12732 com=com,
12733 span=span,
12734 halflife=halflife,
12735 alpha=alpha,
12736 min_periods=min_periods,
12737 adjust=adjust,
12738 ignore_na=ignore_na,
12739 times=times,
12740 method=method,
12741 )
12743 # ----------------------------------------------------------------------
12744 # Arithmetic Methods
12746 @final
12747 def _inplace_method(self, other, op) -> Self:
12748 """
12749 Wrap arithmetic method to operate inplace.
12750 """
12751 result = op(self, other)
12753 # this makes sure that we are aligned like the input
12754 # we are updating inplace
12755 self._update_inplace(result.reindex_like(self))
12756 return self
12758 @final
12759 def __iadd__(self, other) -> Self:
12760 # error: Unsupported left operand type for + ("Type[NDFrame]")
12761 return self._inplace_method(other, type(self).__add__) # type: ignore[operator]
12763 @final
12764 def __isub__(self, other) -> Self:
12765 # error: Unsupported left operand type for - ("Type[NDFrame]")
12766 return self._inplace_method(other, type(self).__sub__) # type: ignore[operator]
12768 @final
12769 def __imul__(self, other) -> Self:
12770 # error: Unsupported left operand type for * ("Type[NDFrame]")
12771 return self._inplace_method(other, type(self).__mul__) # type: ignore[operator]
12773 @final
12774 def __itruediv__(self, other) -> Self:
12775 # error: Unsupported left operand type for / ("Type[NDFrame]")
12776 return self._inplace_method(
12777 other,
12778 type(self).__truediv__, # type: ignore[operator]
12779 )
12781 @final
12782 def __ifloordiv__(self, other) -> Self:
12783 # error: Unsupported left operand type for // ("Type[NDFrame]")
12784 return self._inplace_method(
12785 other,
12786 type(self).__floordiv__, # type: ignore[operator]
12787 )
12789 @final
12790 def __imod__(self, other) -> Self:
12791 # error: Unsupported left operand type for % ("Type[NDFrame]")
12792 return self._inplace_method(other, type(self).__mod__) # type: ignore[operator]
12794 @final
12795 def __ipow__(self, other) -> Self:
12796 # error: Unsupported left operand type for ** ("Type[NDFrame]")
12797 return self._inplace_method(other, type(self).__pow__) # type: ignore[operator]
12799 @final
12800 def __iand__(self, other) -> Self:
12801 # error: Unsupported left operand type for & ("Type[NDFrame]")
12802 return self._inplace_method(other, type(self).__and__) # type: ignore[operator]
12804 @final
12805 def __ior__(self, other) -> Self:
12806 return self._inplace_method(other, type(self).__or__)
12808 @final
12809 def __ixor__(self, other) -> Self:
12810 # error: Unsupported left operand type for ^ ("Type[NDFrame]")
12811 return self._inplace_method(other, type(self).__xor__) # type: ignore[operator]
12813 # ----------------------------------------------------------------------
12814 # Misc methods
12816 @final
12817 def _find_valid_index(self, *, how: str) -> Hashable:
12818 """
12819 Retrieves the index of the first valid value.
12821 Parameters
12822 ----------
12823 how : {'first', 'last'}
12824 Use this parameter to change between the first or last valid index.
12826 Returns
12827 -------
12828 idx_first_valid : type of index
12829 """
12830 is_valid = self.notna().values
12831 idxpos = find_valid_index(how=how, is_valid=is_valid)
12832 if idxpos is None:
12833 return None
12834 return self.index[idxpos]
12836 @final
12837 def first_valid_index(self) -> Hashable:
12838 """
12839 Return index for first non-missing value or None, if no value is found.
12841 See the :ref:`User Guide <missing_data>` for more information
12842 on which values are considered missing.
12844 Returns
12845 -------
12846 type of index
12847 Index of first non-missing value.
12849 See Also
12850 --------
12851 DataFrame.last_valid_index : Return index for last non-NA value or None, if
12852 no non-NA value is found.
12853 Series.last_valid_index : Return index for last non-NA value or None, if no
12854 non-NA value is found.
12855 DataFrame.isna : Detect missing values.
12857 Examples
12858 --------
12859 For Series:
12861 >>> s = pd.Series([None, 3, 4])
12862 >>> s.first_valid_index()
12863 1
12864 >>> s.last_valid_index()
12865 2
12867 >>> s = pd.Series([None, None])
12868 >>> print(s.first_valid_index())
12869 None
12870 >>> print(s.last_valid_index())
12871 None
12873 If all elements in Series are NA/null, returns None.
12875 >>> s = pd.Series()
12876 >>> print(s.first_valid_index())
12877 None
12878 >>> print(s.last_valid_index())
12879 None
12881 If Series is empty, returns None.
12883 For DataFrame:
12885 >>> df = pd.DataFrame({"A": [None, None, 2], "B": [None, 3, 4]})
12886 >>> df
12887 A B
12888 0 NaN NaN
12889 1 NaN 3.0
12890 2 2.0 4.0
12891 >>> df.first_valid_index()
12892 1
12893 >>> df.last_valid_index()
12894 2
12896 >>> df = pd.DataFrame({"A": [None, None, None], "B": [None, None, None]})
12897 >>> df
12898 A B
12899 0 None None
12900 1 None None
12901 2 None None
12902 >>> print(df.first_valid_index())
12903 None
12904 >>> print(df.last_valid_index())
12905 None
12907 If all elements in DataFrame are NA/null, returns None.
12909 >>> df = pd.DataFrame()
12910 >>> df
12911 Empty DataFrame
12912 Columns: []
12913 Index: []
12914 >>> print(df.first_valid_index())
12915 None
12916 >>> print(df.last_valid_index())
12917 None
12919 If DataFrame is empty, returns None.
12920 """
12921 return self._find_valid_index(how="first")
12923 @final
12924 def last_valid_index(self) -> Hashable:
12925 """
12926 Return index for last non-missing value or None, if no value is found.
12928 See the :ref:`User Guide <missing_data>` for more information
12929 on which values are considered missing.
12931 Returns
12932 -------
12933 type of index
12934 Index of last non-missing value.
12936 See Also
12937 --------
12938 DataFrame.first_valid_index : Return index for first non-NA value or None, if
12939 no non-NA value is found.
12940 Series.first_valid_index : Return index for first non-NA value or None, if no
12941 non-NA value is found.
12942 DataFrame.isna : Detect missing values.
12944 Examples
12945 --------
12946 For Series:
12948 >>> s = pd.Series([None, 3, 4])
12949 >>> s.first_valid_index()
12950 1
12951 >>> s.last_valid_index()
12952 2
12954 >>> s = pd.Series([None, None])
12955 >>> print(s.first_valid_index())
12956 None
12957 >>> print(s.last_valid_index())
12958 None
12960 If all elements in Series are NA/null, returns None.
12962 >>> s = pd.Series()
12963 >>> print(s.first_valid_index())
12964 None
12965 >>> print(s.last_valid_index())
12966 None
12968 If Series is empty, returns None.
12970 For DataFrame:
12972 >>> df = pd.DataFrame({"A": [None, None, 2], "B": [None, 3, 4]})
12973 >>> df
12974 A B
12975 0 NaN NaN
12976 1 NaN 3.0
12977 2 2.0 4.0
12978 >>> df.first_valid_index()
12979 1
12980 >>> df.last_valid_index()
12981 2
12983 >>> df = pd.DataFrame({"A": [None, None, None], "B": [None, None, None]})
12984 >>> df
12985 A B
12986 0 None None
12987 1 None None
12988 2 None None
12989 >>> print(df.first_valid_index())
12990 None
12991 >>> print(df.last_valid_index())
12992 None
12994 If all elements in DataFrame are NA/null, returns None.
12996 >>> df = pd.DataFrame()
12997 >>> df
12998 Empty DataFrame
12999 Columns: []
13000 Index: []
13001 >>> print(df.first_valid_index())
13002 None
13003 >>> print(df.last_valid_index())
13004 None
13006 If DataFrame is empty, returns None.
13007 """
13008 return self._find_valid_index(how="last")