Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- lib/python3.12/site-packages/pandas/_libs/__init__.pyAdded+27
- lib/python3.12/site-packages/pandas/_libs/algos.pyiAdded+416
- lib/python3.12/site-packages/pandas/_libs/arrays.pyiAdded+40
- lib/python3.12/site-packages/pandas/_libs/byteswap.cpython-312-x86_64-linux-gnu.soAdded
- lib/python3.12/site-packages/pandas/_libs/byteswap.pyiAdded+5
- lib/python3.12/site-packages/pandas/_libs/groupby.pyiAdded+216
- lib/python3.12/site-packages/pandas/_libs/hashing.pyiAdded+9
- lib/python3.12/site-packages/pandas/_libs/hashtable.pyiAdded+252
- lib/python3.12/site-packages/pandas/_libs/index.pyiAdded+100
- lib/python3.12/site-packages/pandas/_libs/indexing.cpython-312-x86_64-linux-gnu.soAdded
- lib/python3.12/site-packages/pandas/_libs/indexing.pyiAdded+17
- lib/python3.12/site-packages/pandas/_libs/internals.pyiAdded+94
- lib/python3.12/site-packages/pandas/_libs/interval.pyiAdded+174
- lib/python3.12/site-packages/pandas/_libs/join.pyiAdded+79
- lib/python3.12/site-packages/pandas/_libs/json.cpython-312-x86_64-linux-gnu.soAdded
- lib/python3.12/site-packages/pandas/_libs/json.pyiAdded+23
- lib/python3.12/site-packages/pandas/_libs/lib.pyiAdded+213
- lib/python3.12/site-packages/pandas/_libs/missing.pyiAdded+16
- lib/python3.12/site-packages/pandas/_libs/ops.pyiAdded+51
- lib/python3.12/site-packages/pandas/_libs/ops_dispatch.cpython-312-x86_64-linux-gnu.soAdded
- lib/python3.12/site-packages/pandas/_libs/ops_dispatch.pyiAdded+5
- lib/python3.12/site-packages/pandas/_libs/pandas_datetime.cpython-312-x86_64-linux-gnu.soAdded
- lib/python3.12/site-packages/pandas/_libs/pandas_parser.cpython-312-x86_64-linux-gnu.soAdded
- lib/python3.12/site-packages/pandas/_libs/parsers.pyiAdded+77
- lib/python3.12/site-packages/pandas/_libs/properties.cpython-312-x86_64-linux-gnu.soAdded
- lib/python3.12/site-packages/pandas/_libs/properties.pyiAdded+27
- lib/python3.12/site-packages/pandas/_libs/reshape.pyiAdded+16
- lib/python3.12/site-packages/pandas/_libs/sas.pyiAdded+7
- lib/python3.12/site-packages/pandas/_libs/sparse.pyiAdded+51
- lib/python3.12/site-packages/pandas/_libs/testing.pyiAdded+12
- lib/python3.12/site-packages/pandas/_libs/tslib.pyiAdded+37
- lib/python3.12/site-packages/pandas/_libs/writers.pyiAdded+20
- lib/python3.12/site-packages/pandas/core/__init__.pyAdded
- lib/python3.12/site-packages/pandas/core/accessor.pyAdded+340
- lib/python3.12/site-packages/pandas/core/algorithms.pyAdded+1747
- lib/python3.12/site-packages/pandas/core/api.pyAdded+140
- lib/python3.12/site-packages/pandas/core/apply.pyAdded+2062
- lib/python3.12/site-packages/pandas/core/array_algos/__init__.pyAdded+9
- lib/python3.12/site-packages/pandas/core/array_algos/__pycache__/__init__.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/core/array_algos/__pycache__/datetimelike_accumulations.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/core/array_algos/__pycache__/masked_accumulations.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/core/array_algos/__pycache__/masked_reductions.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/core/array_algos/__pycache__/putmask.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/core/array_algos/__pycache__/quantile.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/core/array_algos/__pycache__/replace.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/core/array_algos/__pycache__/take.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/core/array_algos/__pycache__/transforms.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/core/array_algos/datetimelike_accumulations.pyAdded+67
- lib/python3.12/site-packages/pandas/core/array_algos/masked_accumulations.pyAdded+90
- lib/python3.12/site-packages/pandas/core/array_algos/masked_reductions.pyAdded+197
123456789101112131415161718192021222324252627__all__ = [ "NaT", "NaTType", "OutOfBoundsDatetime", "Period", "Timedelta", "Timestamp", "iNaT", "Interval",]
# Below imports needs to happen first to ensure pandas top level# module gets monkeypatched with the pandas_datetime_CAPI# see pandas_datetime_exec in pd_datetime.cimport pandas._libs.pandas_parser # isort: skip # type: ignore[reportUnusedImport]import pandas._libs.pandas_datetime # noqa: F401 # isort: skip # type: ignore[reportUnusedImport]from pandas._libs.interval import Intervalfrom pandas._libs.tslibs import ( NaT, NaTType, OutOfBoundsDatetime, Period, Timedelta, Timestamp, iNaT,)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416from typing import Any
import numpy as np
from pandas._typing import npt
class Infinity: def __eq__(self, other) -> bool: ... def __ne__(self, other) -> bool: ... def __lt__(self, other) -> bool: ... def __le__(self, other) -> bool: ... def __gt__(self, other) -> bool: ... def __ge__(self, other) -> bool: ...
class NegInfinity: def __eq__(self, other) -> bool: ... def __ne__(self, other) -> bool: ... def __lt__(self, other) -> bool: ... def __le__(self, other) -> bool: ... def __gt__(self, other) -> bool: ... def __ge__(self, other) -> bool: ...
def unique_deltas( arr: np.ndarray, # const int64_t[:]) -> np.ndarray: ... # np.ndarray[np.int64, ndim=1]def is_lexsorted(list_of_arrays: list[npt.NDArray[np.int64]]) -> bool: ...def groupsort_indexer( index: np.ndarray, # const int64_t[:] ngroups: int,) -> tuple[ np.ndarray, # ndarray[int64_t, ndim=1] np.ndarray, # ndarray[int64_t, ndim=1]]: ...def kth_smallest( arr: np.ndarray, # numeric[:] k: int,) -> Any: ... # numeric
# ----------------------------------------------------------------------# Pairwise correlation/covariance
def nancorr( mat: npt.NDArray[np.float64], # const float64_t[:, :] cov: bool = ..., minp: int | None = ...,) -> npt.NDArray[np.float64]: ... # ndarray[float64_t, ndim=2]def nancorr_spearman( mat: npt.NDArray[np.float64], # ndarray[float64_t, ndim=2] minp: int = ...,) -> npt.NDArray[np.float64]: ... # ndarray[float64_t, ndim=2]
# ----------------------------------------------------------------------
def validate_limit(nobs: int | None, limit=...) -> int: ...def get_fill_indexer( mask: npt.NDArray[np.bool_], limit: int | None = None,) -> npt.NDArray[np.intp]: ...def pad( old: np.ndarray, # ndarray[numeric_object_t] new: np.ndarray, # ndarray[numeric_object_t] limit=...,) -> npt.NDArray[np.intp]: ... # np.ndarray[np.intp, ndim=1]def pad_inplace( values: np.ndarray, # numeric_object_t[:] mask: np.ndarray, # uint8_t[:] limit=...,) -> None: ...def pad_2d_inplace( values: np.ndarray, # numeric_object_t[:, :] mask: np.ndarray, # const uint8_t[:, :] limit=...,) -> None: ...def backfill( old: np.ndarray, # ndarray[numeric_object_t] new: np.ndarray, # ndarray[numeric_object_t] limit=...,) -> npt.NDArray[np.intp]: ... # np.ndarray[np.intp, ndim=1]def backfill_inplace( values: np.ndarray, # numeric_object_t[:] mask: np.ndarray, # uint8_t[:] limit=...,) -> None: ...def backfill_2d_inplace( values: np.ndarray, # numeric_object_t[:, :] mask: np.ndarray, # const uint8_t[:, :] limit=...,) -> None: ...def is_monotonic( arr: np.ndarray, # ndarray[numeric_object_t, ndim=1] timelike: bool,) -> tuple[bool, bool, bool]: ...
# ----------------------------------------------------------------------# rank_1d, rank_2d# ----------------------------------------------------------------------
def rank_1d( values: np.ndarray, # ndarray[numeric_object_t, ndim=1] labels: np.ndarray | None = ..., # const int64_t[:]=None is_datetimelike: bool = ..., ties_method=..., ascending: bool = ..., pct: bool = ..., na_option=..., mask: npt.NDArray[np.bool_] | None = ...,) -> np.ndarray: ... # np.ndarray[float64_t, ndim=1]def rank_2d( in_arr: np.ndarray, # ndarray[numeric_object_t, ndim=2] axis: int = ..., is_datetimelike: bool = ..., ties_method=..., ascending: bool = ..., na_option=..., pct: bool = ...,) -> np.ndarray: ... # np.ndarray[float64_t, ndim=1]def diff_2d( arr: np.ndarray, # ndarray[diff_t, ndim=2] out: np.ndarray, # ndarray[out_t, ndim=2] periods: int, axis: int, datetimelike: bool = ...,) -> None: ...def ensure_platform_int(arr: object) -> npt.NDArray[np.intp]: ...def ensure_object(arr: object) -> npt.NDArray[np.object_]: ...def ensure_float64(arr: object) -> npt.NDArray[np.float64]: ...def ensure_int8(arr: object) -> npt.NDArray[np.int8]: ...def ensure_int16(arr: object) -> npt.NDArray[np.int16]: ...def ensure_int32(arr: object) -> npt.NDArray[np.int32]: ...def ensure_int64(arr: object) -> npt.NDArray[np.int64]: ...def ensure_uint64(arr: object) -> npt.NDArray[np.uint64]: ...def take_1d_int8_int8( values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...) -> None: ...def take_1d_int8_int32( values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...) -> None: ...def take_1d_int8_int64( values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...) -> None: ...def take_1d_int8_float64( values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...) -> None: ...def take_1d_int16_int16( values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...) -> None: ...def take_1d_int16_int32( values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...) -> None: ...def take_1d_int16_int64( values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...) -> None: ...def take_1d_int16_float64( values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...) -> None: ...def take_1d_int32_int32( values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...) -> None: ...def take_1d_int32_int64( values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...) -> None: ...def take_1d_int32_float64( values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...) -> None: ...def take_1d_int64_int64( values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...) -> None: ...def take_1d_int64_float64( values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...) -> None: ...def take_1d_float32_float32( values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...) -> None: ...def take_1d_float32_float64( values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...) -> None: ...def take_1d_float64_float64( values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...) -> None: ...def take_1d_object_object( values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...) -> None: ...def take_1d_bool_bool( values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...) -> None: ...def take_1d_bool_object( values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...) -> None: ...def take_2d_axis0_int8_int8( values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...) -> None: ...def take_2d_axis0_int8_int32( values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...) -> None: ...def take_2d_axis0_int8_int64( values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...) -> None: ...def take_2d_axis0_int8_float64( values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...) -> None: ...def take_2d_axis0_int16_int16( values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...) -> None: ...def take_2d_axis0_int16_int32( values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...) -> None: ...def take_2d_axis0_int16_int64( values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...) -> None: ...def take_2d_axis0_int16_float64( values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...) -> None: ...def take_2d_axis0_int32_int32( values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...) -> None: ...def take_2d_axis0_int32_int64( values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...) -> None: ...def take_2d_axis0_int32_float64( values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...) -> None: ...def take_2d_axis0_int64_int64( values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...) -> None: ...def take_2d_axis0_int64_float64( values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...) -> None: ...def take_2d_axis0_float32_float32( values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...) -> None: ...def take_2d_axis0_float32_float64( values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...) -> None: ...def take_2d_axis0_float64_float64( values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...) -> None: ...def take_2d_axis0_object_object( values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...) -> None: ...def take_2d_axis0_bool_bool( values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...) -> None: ...def take_2d_axis0_bool_object( values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...) -> None: ...def take_2d_axis1_int8_int8( values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...) -> None: ...def take_2d_axis1_int8_int32( values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...) -> None: ...def take_2d_axis1_int8_int64( values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...) -> None: ...def take_2d_axis1_int8_float64( values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...) -> None: ...def take_2d_axis1_int16_int16( values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...) -> None: ...def take_2d_axis1_int16_int32( values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...) -> None: ...def take_2d_axis1_int16_int64( values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...) -> None: ...def take_2d_axis1_int16_float64( values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...) -> None: ...def take_2d_axis1_int32_int32( values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...) -> None: ...def take_2d_axis1_int32_int64( values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...) -> None: ...def take_2d_axis1_int32_float64( values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...) -> None: ...def take_2d_axis1_int64_int64( values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...) -> None: ...def take_2d_axis1_int64_float64( values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...) -> None: ...def take_2d_axis1_float32_float32( values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...) -> None: ...def take_2d_axis1_float32_float64( values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...) -> None: ...def take_2d_axis1_float64_float64( values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...) -> None: ...def take_2d_axis1_object_object( values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...) -> None: ...def take_2d_axis1_bool_bool( values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...) -> None: ...def take_2d_axis1_bool_object( values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...) -> None: ...def take_2d_multi_int8_int8( values: np.ndarray, indexer: tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]], out: np.ndarray, fill_value=...,) -> None: ...def take_2d_multi_int8_int32( values: np.ndarray, indexer: tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]], out: np.ndarray, fill_value=...,) -> None: ...def take_2d_multi_int8_int64( values: np.ndarray, indexer: tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]], out: np.ndarray, fill_value=...,) -> None: ...def take_2d_multi_int8_float64( values: np.ndarray, indexer: tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]], out: np.ndarray, fill_value=...,) -> None: ...def take_2d_multi_int16_int16( values: np.ndarray, indexer: tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]], out: np.ndarray, fill_value=...,) -> None: ...def take_2d_multi_int16_int32( values: np.ndarray, indexer: tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]], out: np.ndarray, fill_value=...,) -> None: ...def take_2d_multi_int16_int64( values: np.ndarray, indexer: tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]], out: np.ndarray, fill_value=...,) -> None: ...def take_2d_multi_int16_float64( values: np.ndarray, indexer: tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]], out: np.ndarray, fill_value=...,) -> None: ...def take_2d_multi_int32_int32( values: np.ndarray, indexer: tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]], out: np.ndarray, fill_value=...,) -> None: ...def take_2d_multi_int32_int64( values: np.ndarray, indexer: tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]], out: np.ndarray, fill_value=...,) -> None: ...def take_2d_multi_int32_float64( values: np.ndarray, indexer: tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]], out: np.ndarray, fill_value=...,) -> None: ...def take_2d_multi_int64_float64( values: np.ndarray, indexer: tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]], out: np.ndarray, fill_value=...,) -> None: ...def take_2d_multi_float32_float32( values: np.ndarray, indexer: tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]], out: np.ndarray, fill_value=...,) -> None: ...def take_2d_multi_float32_float64( values: np.ndarray, indexer: tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]], out: np.ndarray, fill_value=...,) -> None: ...def take_2d_multi_float64_float64( values: np.ndarray, indexer: tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]], out: np.ndarray, fill_value=...,) -> None: ...def take_2d_multi_object_object( values: np.ndarray, indexer: tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]], out: np.ndarray, fill_value=...,) -> None: ...def take_2d_multi_bool_bool( values: np.ndarray, indexer: tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]], out: np.ndarray, fill_value=...,) -> None: ...def take_2d_multi_bool_object( values: np.ndarray, indexer: tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]], out: np.ndarray, fill_value=...,) -> None: ...def take_2d_multi_int64_int64( values: np.ndarray, indexer: tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]], out: np.ndarray, fill_value=...,) -> None: ...12345678910111213141516171819202122232425262728293031323334353637383940from typing import Sequence
import numpy as np
from pandas._typing import ( AxisInt, DtypeObj, Self, Shape,)
class NDArrayBacked: _dtype: DtypeObj _ndarray: np.ndarray def __init__(self, values: np.ndarray, dtype: DtypeObj) -> None: ... @classmethod def _simple_new(cls, values: np.ndarray, dtype: DtypeObj): ... def _from_backing_data(self, values: np.ndarray): ... def __setstate__(self, state): ... def __len__(self) -> int: ... @property def shape(self) -> Shape: ... @property def ndim(self) -> int: ... @property def size(self) -> int: ... @property def nbytes(self) -> int: ... def copy(self, order=...): ... def delete(self, loc, axis=...): ... def swapaxes(self, axis1, axis2): ... def repeat(self, repeats: int | Sequence[int], axis: int | None = ...): ... def reshape(self, *args, **kwargs): ... def ravel(self, order=...): ... @property def T(self): ... @classmethod def _concat_same_type( cls, to_concat: Sequence[Self], axis: AxisInt = ... ) -> Self: ...12345def read_float_with_byteswap(data: bytes, offset: int, byteswap: bool) -> float: ...def read_double_with_byteswap(data: bytes, offset: int, byteswap: bool) -> float: ...def read_uint16_with_byteswap(data: bytes, offset: int, byteswap: bool) -> int: ...def read_uint32_with_byteswap(data: bytes, offset: int, byteswap: bool) -> int: ...def read_uint64_with_byteswap(data: bytes, offset: int, byteswap: bool) -> int: ...123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216from typing import Literal
import numpy as np
from pandas._typing import npt
def group_median_float64( out: np.ndarray, # ndarray[float64_t, ndim=2] counts: npt.NDArray[np.int64], values: np.ndarray, # ndarray[float64_t, ndim=2] labels: npt.NDArray[np.int64], min_count: int = ..., # Py_ssize_t mask: np.ndarray | None = ..., result_mask: np.ndarray | None = ...,) -> None: ...def group_cumprod( out: np.ndarray, # float64_t[:, ::1] values: np.ndarray, # const float64_t[:, :] labels: np.ndarray, # const int64_t[:] ngroups: int, is_datetimelike: bool, skipna: bool = ..., mask: np.ndarray | None = ..., result_mask: np.ndarray | None = ...,) -> None: ...def group_cumsum( out: np.ndarray, # int64float_t[:, ::1] values: np.ndarray, # ndarray[int64float_t, ndim=2] labels: np.ndarray, # const int64_t[:] ngroups: int, is_datetimelike: bool, skipna: bool = ..., mask: np.ndarray | None = ..., result_mask: np.ndarray | None = ...,) -> None: ...def group_shift_indexer( out: np.ndarray, # int64_t[::1] labels: np.ndarray, # const int64_t[:] ngroups: int, periods: int,) -> None: ...def group_fillna_indexer( out: np.ndarray, # ndarray[intp_t] labels: np.ndarray, # ndarray[int64_t] sorted_labels: npt.NDArray[np.intp], mask: npt.NDArray[np.uint8], limit: int, # int64_t dropna: bool,) -> None: ...def group_any_all( out: np.ndarray, # uint8_t[::1] values: np.ndarray, # const uint8_t[::1] labels: np.ndarray, # const int64_t[:] mask: np.ndarray, # const uint8_t[::1] val_test: Literal["any", "all"], skipna: bool, result_mask: np.ndarray | None,) -> None: ...def group_sum( out: np.ndarray, # complexfloatingintuint_t[:, ::1] counts: np.ndarray, # int64_t[::1] values: np.ndarray, # ndarray[complexfloatingintuint_t, ndim=2] labels: np.ndarray, # const intp_t[:] mask: np.ndarray | None, result_mask: np.ndarray | None = ..., min_count: int = ..., is_datetimelike: bool = ...,) -> None: ...def group_prod( out: np.ndarray, # int64float_t[:, ::1] counts: np.ndarray, # int64_t[::1] values: np.ndarray, # ndarray[int64float_t, ndim=2] labels: np.ndarray, # const intp_t[:] mask: np.ndarray | None, result_mask: np.ndarray | None = ..., min_count: int = ...,) -> None: ...def group_var( out: np.ndarray, # floating[:, ::1] counts: np.ndarray, # int64_t[::1] values: np.ndarray, # ndarray[floating, ndim=2] labels: np.ndarray, # const intp_t[:] min_count: int = ..., # Py_ssize_t ddof: int = ..., # int64_t mask: np.ndarray | None = ..., result_mask: np.ndarray | None = ..., is_datetimelike: bool = ..., name: str = ...,) -> None: ...def group_skew( out: np.ndarray, # float64_t[:, ::1] counts: np.ndarray, # int64_t[::1] values: np.ndarray, # ndarray[float64_T, ndim=2] labels: np.ndarray, # const intp_t[::1] mask: np.ndarray | None = ..., result_mask: np.ndarray | None = ..., skipna: bool = ...,) -> None: ...def group_mean( out: np.ndarray, # floating[:, ::1] counts: np.ndarray, # int64_t[::1] values: np.ndarray, # ndarray[floating, ndim=2] labels: np.ndarray, # const intp_t[:] min_count: int = ..., # Py_ssize_t is_datetimelike: bool = ..., # bint mask: np.ndarray | None = ..., result_mask: np.ndarray | None = ...,) -> None: ...def group_ohlc( out: np.ndarray, # floatingintuint_t[:, ::1] counts: np.ndarray, # int64_t[::1] values: np.ndarray, # ndarray[floatingintuint_t, ndim=2] labels: np.ndarray, # const intp_t[:] min_count: int = ..., mask: np.ndarray | None = ..., result_mask: np.ndarray | None = ...,) -> None: ...def group_quantile( out: npt.NDArray[np.float64], values: np.ndarray, # ndarray[numeric, ndim=1] labels: npt.NDArray[np.intp], mask: npt.NDArray[np.uint8], qs: npt.NDArray[np.float64], # const starts: npt.NDArray[np.int64], ends: npt.NDArray[np.int64], interpolation: Literal["linear", "lower", "higher", "nearest", "midpoint"], result_mask: np.ndarray | None, is_datetimelike: bool,) -> None: ...def group_last( out: np.ndarray, # rank_t[:, ::1] counts: np.ndarray, # int64_t[::1] values: np.ndarray, # ndarray[rank_t, ndim=2] labels: np.ndarray, # const int64_t[:] mask: npt.NDArray[np.bool_] | None, result_mask: npt.NDArray[np.bool_] | None = ..., min_count: int = ..., # Py_ssize_t is_datetimelike: bool = ..., skipna: bool = ...,) -> None: ...def group_nth( out: np.ndarray, # rank_t[:, ::1] counts: np.ndarray, # int64_t[::1] values: np.ndarray, # ndarray[rank_t, ndim=2] labels: np.ndarray, # const int64_t[:] mask: npt.NDArray[np.bool_] | None, result_mask: npt.NDArray[np.bool_] | None = ..., min_count: int = ..., # int64_t rank: int = ..., # int64_t is_datetimelike: bool = ..., skipna: bool = ...,) -> None: ...def group_rank( out: np.ndarray, # float64_t[:, ::1] values: np.ndarray, # ndarray[rank_t, ndim=2] labels: np.ndarray, # const int64_t[:] ngroups: int, is_datetimelike: bool, ties_method: Literal["average", "min", "max", "first", "dense"] = ..., ascending: bool = ..., pct: bool = ..., na_option: Literal["keep", "top", "bottom"] = ..., mask: npt.NDArray[np.bool_] | None = ...,) -> None: ...def group_max( out: np.ndarray, # groupby_t[:, ::1] counts: np.ndarray, # int64_t[::1] values: np.ndarray, # ndarray[groupby_t, ndim=2] labels: np.ndarray, # const int64_t[:] min_count: int = ..., is_datetimelike: bool = ..., mask: np.ndarray | None = ..., result_mask: np.ndarray | None = ...,) -> None: ...def group_min( out: np.ndarray, # groupby_t[:, ::1] counts: np.ndarray, # int64_t[::1] values: np.ndarray, # ndarray[groupby_t, ndim=2] labels: np.ndarray, # const int64_t[:] min_count: int = ..., is_datetimelike: bool = ..., mask: np.ndarray | None = ..., result_mask: np.ndarray | None = ...,) -> None: ...def group_idxmin_idxmax( out: npt.NDArray[np.intp], counts: npt.NDArray[np.int64], values: np.ndarray, # ndarray[groupby_t, ndim=2] labels: npt.NDArray[np.intp], min_count: int = ..., is_datetimelike: bool = ..., mask: np.ndarray | None = ..., name: str = ..., skipna: bool = ..., result_mask: np.ndarray | None = ...,) -> None: ...def group_cummin( out: np.ndarray, # groupby_t[:, ::1] values: np.ndarray, # ndarray[groupby_t, ndim=2] labels: np.ndarray, # const int64_t[:] ngroups: int, is_datetimelike: bool, mask: np.ndarray | None = ..., result_mask: np.ndarray | None = ..., skipna: bool = ...,) -> None: ...def group_cummax( out: np.ndarray, # groupby_t[:, ::1] values: np.ndarray, # ndarray[groupby_t, ndim=2] labels: np.ndarray, # const int64_t[:] ngroups: int, is_datetimelike: bool, mask: np.ndarray | None = ..., result_mask: np.ndarray | None = ..., skipna: bool = ...,) -> None: ...123456789import numpy as np
from pandas._typing import npt
def hash_object_array( arr: npt.NDArray[np.object_], key: str, encoding: str = ...,) -> npt.NDArray[np.uint64]: ...123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252from typing import ( Any, Hashable, Literal,)
import numpy as np
from pandas._typing import npt
def unique_label_indices( labels: np.ndarray, # const int64_t[:]) -> np.ndarray: ...
class Factorizer: count: int uniques: Any def __init__(self, size_hint: int) -> None: ... def get_count(self) -> int: ... def factorize( self, values: np.ndarray, na_sentinel=..., na_value=..., mask=..., ) -> npt.NDArray[np.intp]: ...
class ObjectFactorizer(Factorizer): table: PyObjectHashTable uniques: ObjectVector
class Int64Factorizer(Factorizer): table: Int64HashTable uniques: Int64Vector
class UInt64Factorizer(Factorizer): table: UInt64HashTable uniques: UInt64Vector
class Int32Factorizer(Factorizer): table: Int32HashTable uniques: Int32Vector
class UInt32Factorizer(Factorizer): table: UInt32HashTable uniques: UInt32Vector
class Int16Factorizer(Factorizer): table: Int16HashTable uniques: Int16Vector
class UInt16Factorizer(Factorizer): table: UInt16HashTable uniques: UInt16Vector
class Int8Factorizer(Factorizer): table: Int8HashTable uniques: Int8Vector
class UInt8Factorizer(Factorizer): table: UInt8HashTable uniques: UInt8Vector
class Float64Factorizer(Factorizer): table: Float64HashTable uniques: Float64Vector
class Float32Factorizer(Factorizer): table: Float32HashTable uniques: Float32Vector
class Complex64Factorizer(Factorizer): table: Complex64HashTable uniques: Complex64Vector
class Complex128Factorizer(Factorizer): table: Complex128HashTable uniques: Complex128Vector
class Int64Vector: def __init__(self, *args) -> None: ... def __len__(self) -> int: ... def to_array(self) -> npt.NDArray[np.int64]: ...
class Int32Vector: def __init__(self, *args) -> None: ... def __len__(self) -> int: ... def to_array(self) -> npt.NDArray[np.int32]: ...
class Int16Vector: def __init__(self, *args) -> None: ... def __len__(self) -> int: ... def to_array(self) -> npt.NDArray[np.int16]: ...
class Int8Vector: def __init__(self, *args) -> None: ... def __len__(self) -> int: ... def to_array(self) -> npt.NDArray[np.int8]: ...
class UInt64Vector: def __init__(self, *args) -> None: ... def __len__(self) -> int: ... def to_array(self) -> npt.NDArray[np.uint64]: ...
class UInt32Vector: def __init__(self, *args) -> None: ... def __len__(self) -> int: ... def to_array(self) -> npt.NDArray[np.uint32]: ...
class UInt16Vector: def __init__(self, *args) -> None: ... def __len__(self) -> int: ... def to_array(self) -> npt.NDArray[np.uint16]: ...
class UInt8Vector: def __init__(self, *args) -> None: ... def __len__(self) -> int: ... def to_array(self) -> npt.NDArray[np.uint8]: ...
class Float64Vector: def __init__(self, *args) -> None: ... def __len__(self) -> int: ... def to_array(self) -> npt.NDArray[np.float64]: ...
class Float32Vector: def __init__(self, *args) -> None: ... def __len__(self) -> int: ... def to_array(self) -> npt.NDArray[np.float32]: ...
class Complex128Vector: def __init__(self, *args) -> None: ... def __len__(self) -> int: ... def to_array(self) -> npt.NDArray[np.complex128]: ...
class Complex64Vector: def __init__(self, *args) -> None: ... def __len__(self) -> int: ... def to_array(self) -> npt.NDArray[np.complex64]: ...
class StringVector: def __init__(self, *args) -> None: ... def __len__(self) -> int: ... def to_array(self) -> npt.NDArray[np.object_]: ...
class ObjectVector: def __init__(self, *args) -> None: ... def __len__(self) -> int: ... def to_array(self) -> npt.NDArray[np.object_]: ...
class HashTable: # NB: The base HashTable class does _not_ actually have these methods; # we are putting them here for the sake of mypy to avoid # reproducing them in each subclass below. def __init__(self, size_hint: int = ..., uses_mask: bool = ...) -> None: ... def __len__(self) -> int: ... def __contains__(self, key: Hashable) -> bool: ... def sizeof(self, deep: bool = ...) -> int: ... def get_state(self) -> dict[str, int]: ... # TODO: `val/key` type is subclass-specific def get_item(self, val): ... # TODO: return type? def set_item(self, key, val) -> None: ... def get_na(self): ... # TODO: return type? def set_na(self, val) -> None: ... def map_locations( self, values: np.ndarray, # np.ndarray[subclass-specific] mask: npt.NDArray[np.bool_] | None = ..., ) -> None: ... def lookup( self, values: np.ndarray, # np.ndarray[subclass-specific] mask: npt.NDArray[np.bool_] | None = ..., ) -> npt.NDArray[np.intp]: ... def get_labels( self, values: np.ndarray, # np.ndarray[subclass-specific] uniques, # SubclassTypeVector count_prior: int = ..., na_sentinel: int = ..., na_value: object = ..., mask=..., ) -> npt.NDArray[np.intp]: ... def unique( self, values: np.ndarray, # np.ndarray[subclass-specific] return_inverse: bool = ..., mask=..., ) -> ( tuple[ np.ndarray, # np.ndarray[subclass-specific] npt.NDArray[np.intp], ] | np.ndarray ): ... # np.ndarray[subclass-specific] def factorize( self, values: np.ndarray, # np.ndarray[subclass-specific] na_sentinel: int = ..., na_value: object = ..., mask=..., ignore_na: bool = True, ) -> tuple[np.ndarray, npt.NDArray[np.intp]]: ... # np.ndarray[subclass-specific]
class Complex128HashTable(HashTable): ...class Complex64HashTable(HashTable): ...class Float64HashTable(HashTable): ...class Float32HashTable(HashTable): ...
class Int64HashTable(HashTable): # Only Int64HashTable has get_labels_groupby, map_keys_to_values def get_labels_groupby( self, values: npt.NDArray[np.int64], # const int64_t[:] ) -> tuple[npt.NDArray[np.intp], npt.NDArray[np.int64]]: ... def map_keys_to_values( self, keys: npt.NDArray[np.int64], values: npt.NDArray[np.int64], # const int64_t[:] ) -> None: ...
class Int32HashTable(HashTable): ...class Int16HashTable(HashTable): ...class Int8HashTable(HashTable): ...class UInt64HashTable(HashTable): ...class UInt32HashTable(HashTable): ...class UInt16HashTable(HashTable): ...class UInt8HashTable(HashTable): ...class StringHashTable(HashTable): ...class PyObjectHashTable(HashTable): ...class IntpHashTable(HashTable): ...
def duplicated( values: np.ndarray, keep: Literal["last", "first", False] = ..., mask: npt.NDArray[np.bool_] | None = ...,) -> npt.NDArray[np.bool_]: ...def mode( values: np.ndarray, dropna: bool, mask: npt.NDArray[np.bool_] | None = ...) -> np.ndarray: ...def value_count( values: np.ndarray, dropna: bool, mask: npt.NDArray[np.bool_] | None = ...,) -> tuple[np.ndarray, npt.NDArray[np.int64], int]: ... # np.ndarray[same-as-values]
# arr and values should have same dtypedef ismember( arr: np.ndarray, values: np.ndarray,) -> npt.NDArray[np.bool_]: ...def object_hash(obj) -> int: ...def objects_are_equal(a, b) -> bool: ...123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100import numpy as np
from pandas._typing import npt
from pandas import MultiIndexfrom pandas.core.arrays import ExtensionArray
multiindex_nulls_shift: int
class IndexEngine: over_size_threshold: bool def __init__(self, values: np.ndarray) -> None: ... def __contains__(self, val: object) -> bool: ...
# -> int | slice | np.ndarray[bool] def get_loc(self, val: object) -> int | slice | np.ndarray: ... def sizeof(self, deep: bool = ...) -> int: ... def __sizeof__(self) -> int: ... @property def is_unique(self) -> bool: ... @property def is_monotonic_increasing(self) -> bool: ... @property def is_monotonic_decreasing(self) -> bool: ... @property def is_mapping_populated(self) -> bool: ... def clear_mapping(self): ... def get_indexer(self, values: np.ndarray) -> npt.NDArray[np.intp]: ... def get_indexer_non_unique( self, targets: np.ndarray, ) -> tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]]: ...
class MaskedIndexEngine(IndexEngine): def __init__(self, values: object) -> None: ... def get_indexer_non_unique( self, targets: object ) -> tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]]: ...
class Float64Engine(IndexEngine): ...class Float32Engine(IndexEngine): ...class Complex128Engine(IndexEngine): ...class Complex64Engine(IndexEngine): ...class Int64Engine(IndexEngine): ...class Int32Engine(IndexEngine): ...class Int16Engine(IndexEngine): ...class Int8Engine(IndexEngine): ...class UInt64Engine(IndexEngine): ...class UInt32Engine(IndexEngine): ...class UInt16Engine(IndexEngine): ...class UInt8Engine(IndexEngine): ...class ObjectEngine(IndexEngine): ...class DatetimeEngine(Int64Engine): ...class TimedeltaEngine(DatetimeEngine): ...class PeriodEngine(Int64Engine): ...class BoolEngine(UInt8Engine): ...class MaskedFloat64Engine(MaskedIndexEngine): ...class MaskedFloat32Engine(MaskedIndexEngine): ...class MaskedComplex128Engine(MaskedIndexEngine): ...class MaskedComplex64Engine(MaskedIndexEngine): ...class MaskedInt64Engine(MaskedIndexEngine): ...class MaskedInt32Engine(MaskedIndexEngine): ...class MaskedInt16Engine(MaskedIndexEngine): ...class MaskedInt8Engine(MaskedIndexEngine): ...class MaskedUInt64Engine(MaskedIndexEngine): ...class MaskedUInt32Engine(MaskedIndexEngine): ...class MaskedUInt16Engine(MaskedIndexEngine): ...class MaskedUInt8Engine(MaskedIndexEngine): ...class MaskedBoolEngine(MaskedUInt8Engine): ...
class BaseMultiIndexCodesEngine: levels: list[np.ndarray] offsets: np.ndarray # ndarray[uint64_t, ndim=1]
def __init__( self, levels: list[np.ndarray], # all entries hashable labels: list[np.ndarray], # all entries integer-dtyped offsets: np.ndarray, # np.ndarray[np.uint64, ndim=1] ) -> None: ... def get_indexer(self, target: npt.NDArray[np.object_]) -> npt.NDArray[np.intp]: ... def _extract_level_codes(self, target: MultiIndex) -> np.ndarray: ...
class ExtensionEngine: def __init__(self, values: ExtensionArray) -> None: ... def __contains__(self, val: object) -> bool: ... def get_loc(self, val: object) -> int | slice | np.ndarray: ... def get_indexer(self, values: np.ndarray) -> npt.NDArray[np.intp]: ... def get_indexer_non_unique( self, targets: np.ndarray, ) -> tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]]: ... @property def is_unique(self) -> bool: ... @property def is_monotonic_increasing(self) -> bool: ... @property def is_monotonic_decreasing(self) -> bool: ... def sizeof(self, deep: bool = ...) -> int: ... def clear_mapping(self): ...1234567891011121314151617from typing import ( Generic, TypeVar,)
from pandas.core.indexing import IndexingMixin
_IndexingMixinT = TypeVar("_IndexingMixinT", bound=IndexingMixin)
class NDFrameIndexerBase(Generic[_IndexingMixinT]): name: str # in practice obj is either a DataFrame or a Series obj: _IndexingMixinT
def __init__(self, name: str, obj: _IndexingMixinT) -> None: ... @property def ndim(self) -> int: ...12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394from typing import ( Iterator, Sequence, final, overload,)import weakref
import numpy as np
from pandas._typing import ( ArrayLike, Self, npt,)
from pandas import Indexfrom pandas.core.internals.blocks import Block as B
def slice_len(slc: slice, objlen: int = ...) -> int: ...def get_concat_blkno_indexers( blknos_list: list[npt.NDArray[np.intp]],) -> list[tuple[npt.NDArray[np.intp], BlockPlacement]]: ...def get_blkno_indexers( blknos: np.ndarray, # int64_t[:] group: bool = ...,) -> list[tuple[int, slice | np.ndarray]]: ...def get_blkno_placements( blknos: np.ndarray, group: bool = ...,) -> Iterator[tuple[int, BlockPlacement]]: ...def update_blklocs_and_blknos( blklocs: npt.NDArray[np.intp], blknos: npt.NDArray[np.intp], loc: int, nblocks: int,) -> tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]]: ...@finalclass BlockPlacement: def __init__(self, val: int | slice | np.ndarray) -> None: ... @property def indexer(self) -> np.ndarray | slice: ... @property def as_array(self) -> np.ndarray: ... @property def as_slice(self) -> slice: ... @property def is_slice_like(self) -> bool: ... @overload def __getitem__( self, loc: slice | Sequence[int] | npt.NDArray[np.intp] ) -> BlockPlacement: ... @overload def __getitem__(self, loc: int) -> int: ... def __iter__(self) -> Iterator[int]: ... def __len__(self) -> int: ... def delete(self, loc) -> BlockPlacement: ... def add(self, other) -> BlockPlacement: ... def append(self, others: list[BlockPlacement]) -> BlockPlacement: ... def tile_for_unstack(self, factor: int) -> npt.NDArray[np.intp]: ...
class Block: _mgr_locs: BlockPlacement ndim: int values: ArrayLike refs: BlockValuesRefs def __init__( self, values: ArrayLike, placement: BlockPlacement, ndim: int, refs: BlockValuesRefs | None = ..., ) -> None: ... def slice_block_rows(self, slicer: slice) -> Self: ...
class BlockManager: blocks: tuple[B, ...] axes: list[Index] _known_consolidated: bool _is_consolidated: bool _blknos: np.ndarray _blklocs: np.ndarray def __init__( self, blocks: tuple[B, ...], axes: list[Index], verify_integrity=... ) -> None: ... def get_slice(self, slobj: slice, axis: int = ...) -> Self: ... def _rebuild_blknos_and_blklocs(self) -> None: ...
class BlockValuesRefs: referenced_blocks: list[weakref.ref] def __init__(self, blk: Block | None = ...) -> None: ... def add_reference(self, blk: Block) -> None: ... def add_index_reference(self, index: Index) -> None: ... def has_reference(self) -> bool: ...123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174from typing import ( Any, Generic, TypeVar, overload,)
import numpy as npimport numpy.typing as npt
from pandas._typing import ( IntervalClosedType, Timedelta, Timestamp,)
VALID_CLOSED: frozenset[str]
_OrderableScalarT = TypeVar("_OrderableScalarT", int, float)_OrderableTimesT = TypeVar("_OrderableTimesT", Timestamp, Timedelta)_OrderableT = TypeVar("_OrderableT", int, float, Timestamp, Timedelta)
class _LengthDescriptor: @overload def __get__( self, instance: Interval[_OrderableScalarT], owner: Any ) -> _OrderableScalarT: ... @overload def __get__( self, instance: Interval[_OrderableTimesT], owner: Any ) -> Timedelta: ...
class _MidDescriptor: @overload def __get__(self, instance: Interval[_OrderableScalarT], owner: Any) -> float: ... @overload def __get__( self, instance: Interval[_OrderableTimesT], owner: Any ) -> _OrderableTimesT: ...
class IntervalMixin: @property def closed_left(self) -> bool: ... @property def closed_right(self) -> bool: ... @property def open_left(self) -> bool: ... @property def open_right(self) -> bool: ... @property def is_empty(self) -> bool: ... def _check_closed_matches(self, other: IntervalMixin, name: str = ...) -> None: ...
class Interval(IntervalMixin, Generic[_OrderableT]): @property def left(self: Interval[_OrderableT]) -> _OrderableT: ... @property def right(self: Interval[_OrderableT]) -> _OrderableT: ... @property def closed(self) -> IntervalClosedType: ... mid: _MidDescriptor length: _LengthDescriptor def __init__( self, left: _OrderableT, right: _OrderableT, closed: IntervalClosedType = ..., ) -> None: ... def __hash__(self) -> int: ... @overload def __contains__( self: Interval[Timedelta], key: Timedelta | Interval[Timedelta] ) -> bool: ... @overload def __contains__( self: Interval[Timestamp], key: Timestamp | Interval[Timestamp] ) -> bool: ... @overload def __contains__( self: Interval[_OrderableScalarT], key: _OrderableScalarT | Interval[_OrderableScalarT], ) -> bool: ... @overload def __add__( self: Interval[_OrderableTimesT], y: Timedelta ) -> Interval[_OrderableTimesT]: ... @overload def __add__( self: Interval[int], y: _OrderableScalarT ) -> Interval[_OrderableScalarT]: ... @overload def __add__(self: Interval[float], y: float) -> Interval[float]: ... @overload def __radd__( self: Interval[_OrderableTimesT], y: Timedelta ) -> Interval[_OrderableTimesT]: ... @overload def __radd__( self: Interval[int], y: _OrderableScalarT ) -> Interval[_OrderableScalarT]: ... @overload def __radd__(self: Interval[float], y: float) -> Interval[float]: ... @overload def __sub__( self: Interval[_OrderableTimesT], y: Timedelta ) -> Interval[_OrderableTimesT]: ... @overload def __sub__( self: Interval[int], y: _OrderableScalarT ) -> Interval[_OrderableScalarT]: ... @overload def __sub__(self: Interval[float], y: float) -> Interval[float]: ... @overload def __rsub__( self: Interval[_OrderableTimesT], y: Timedelta ) -> Interval[_OrderableTimesT]: ... @overload def __rsub__( self: Interval[int], y: _OrderableScalarT ) -> Interval[_OrderableScalarT]: ... @overload def __rsub__(self: Interval[float], y: float) -> Interval[float]: ... @overload def __mul__( self: Interval[int], y: _OrderableScalarT ) -> Interval[_OrderableScalarT]: ... @overload def __mul__(self: Interval[float], y: float) -> Interval[float]: ... @overload def __rmul__( self: Interval[int], y: _OrderableScalarT ) -> Interval[_OrderableScalarT]: ... @overload def __rmul__(self: Interval[float], y: float) -> Interval[float]: ... @overload def __truediv__( self: Interval[int], y: _OrderableScalarT ) -> Interval[_OrderableScalarT]: ... @overload def __truediv__(self: Interval[float], y: float) -> Interval[float]: ... @overload def __floordiv__( self: Interval[int], y: _OrderableScalarT ) -> Interval[_OrderableScalarT]: ... @overload def __floordiv__(self: Interval[float], y: float) -> Interval[float]: ... def overlaps(self: Interval[_OrderableT], other: Interval[_OrderableT]) -> bool: ...
def intervals_to_interval_bounds( intervals: np.ndarray, validate_closed: bool = ...) -> tuple[np.ndarray, np.ndarray, IntervalClosedType]: ...
class IntervalTree(IntervalMixin): def __init__( self, left: np.ndarray, right: np.ndarray, closed: IntervalClosedType = ..., leaf_size: int = ..., ) -> None: ... @property def mid(self) -> np.ndarray: ... @property def length(self) -> np.ndarray: ... def get_indexer(self, target) -> npt.NDArray[np.intp]: ... def get_indexer_non_unique( self, target ) -> tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]]: ... _na_count: int @property def is_overlapping(self) -> bool: ... @property def is_monotonic_increasing(self) -> bool: ... def clear_mapping(self) -> None: ...12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879import numpy as np
from pandas._typing import npt
def inner_join( left: np.ndarray, # const intp_t[:] right: np.ndarray, # const intp_t[:] max_groups: int, sort: bool = ...,) -> tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]]: ...def left_outer_join( left: np.ndarray, # const intp_t[:] right: np.ndarray, # const intp_t[:] max_groups: int, sort: bool = ...,) -> tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]]: ...def full_outer_join( left: np.ndarray, # const intp_t[:] right: np.ndarray, # const intp_t[:] max_groups: int,) -> tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]]: ...def ffill_indexer( indexer: np.ndarray, # const intp_t[:]) -> npt.NDArray[np.intp]: ...def left_join_indexer_unique( left: np.ndarray, # ndarray[join_t] right: np.ndarray, # ndarray[join_t]) -> npt.NDArray[np.intp]: ...def left_join_indexer( left: np.ndarray, # ndarray[join_t] right: np.ndarray, # ndarray[join_t]) -> tuple[ np.ndarray, # np.ndarray[join_t] npt.NDArray[np.intp], npt.NDArray[np.intp],]: ...def inner_join_indexer( left: np.ndarray, # ndarray[join_t] right: np.ndarray, # ndarray[join_t]) -> tuple[ np.ndarray, # np.ndarray[join_t] npt.NDArray[np.intp], npt.NDArray[np.intp],]: ...def outer_join_indexer( left: np.ndarray, # ndarray[join_t] right: np.ndarray, # ndarray[join_t]) -> tuple[ np.ndarray, # np.ndarray[join_t] npt.NDArray[np.intp], npt.NDArray[np.intp],]: ...def asof_join_backward_on_X_by_Y( left_values: np.ndarray, # ndarray[numeric_t] right_values: np.ndarray, # ndarray[numeric_t] left_by_values: np.ndarray, # const int64_t[:] right_by_values: np.ndarray, # const int64_t[:] allow_exact_matches: bool = ..., tolerance: np.number | float | None = ..., use_hashtable: bool = ...,) -> tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]]: ...def asof_join_forward_on_X_by_Y( left_values: np.ndarray, # ndarray[numeric_t] right_values: np.ndarray, # ndarray[numeric_t] left_by_values: np.ndarray, # const int64_t[:] right_by_values: np.ndarray, # const int64_t[:] allow_exact_matches: bool = ..., tolerance: np.number | float | None = ..., use_hashtable: bool = ...,) -> tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]]: ...def asof_join_nearest_on_X_by_Y( left_values: np.ndarray, # ndarray[numeric_t] right_values: np.ndarray, # ndarray[numeric_t] left_by_values: np.ndarray, # const int64_t[:] right_by_values: np.ndarray, # const int64_t[:] allow_exact_matches: bool = ..., tolerance: np.number | float | None = ..., use_hashtable: bool = ...,) -> tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]]: ...1234567891011121314151617181920212223from typing import ( Any, Callable,)
def ujson_dumps( obj: Any, ensure_ascii: bool = ..., double_precision: int = ..., indent: int = ..., orient: str = ..., date_unit: str = ..., iso_dates: bool = ..., default_handler: None | Callable[[Any], str | float | bool | list | dict | None] = ...,) -> str: ...def ujson_loads( s: str, precise_float: bool = ..., numpy: bool = ..., dtype: None = ..., labelled: bool = ...,) -> Any: ...123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213# TODO(npdtypes): Many types specified here can be made more specific/accurate;# the more specific versions are specified in commentsfrom decimal import Decimalfrom typing import ( Any, Callable, Final, Generator, Hashable, Literal, TypeAlias, overload,)
import numpy as np
from pandas._libs.interval import Intervalfrom pandas._libs.tslibs import Periodfrom pandas._typing import ( ArrayLike, DtypeObj, TypeGuard, npt,)
# placeholder until we can specify np.ndarray[object, ndim=2]ndarray_obj_2d = np.ndarray
from enum import Enum
class _NoDefault(Enum): no_default = ...
no_default: Final = _NoDefault.no_defaultNoDefault: TypeAlias = Literal[_NoDefault.no_default]
i8max: intu8max: int
def is_np_dtype(dtype: object, kinds: str | None = ...) -> TypeGuard[np.dtype]: ...def item_from_zerodim(val: object) -> object: ...def infer_dtype(value: object, skipna: bool = ...) -> str: ...def is_iterator(obj: object) -> bool: ...def is_scalar(val: object) -> bool: ...def is_list_like(obj: object, allow_sets: bool = ...) -> bool: ...def is_pyarrow_array(obj: object) -> bool: ...def is_period(val: object) -> TypeGuard[Period]: ...def is_interval(obj: object) -> TypeGuard[Interval]: ...def is_decimal(obj: object) -> TypeGuard[Decimal]: ...def is_complex(obj: object) -> TypeGuard[complex]: ...def is_bool(obj: object) -> TypeGuard[bool | np.bool_]: ...def is_integer(obj: object) -> TypeGuard[int | np.integer]: ...def is_int_or_none(obj) -> bool: ...def is_float(obj: object) -> TypeGuard[float]: ...def is_interval_array(values: np.ndarray) -> bool: ...def is_datetime64_array(values: np.ndarray, skipna: bool = True) -> bool: ...def is_timedelta_or_timedelta64_array( values: np.ndarray, skipna: bool = True) -> bool: ...def is_datetime_with_singletz_array(values: np.ndarray) -> bool: ...def is_time_array(values: np.ndarray, skipna: bool = ...): ...def is_date_array(values: np.ndarray, skipna: bool = ...): ...def is_datetime_array(values: np.ndarray, skipna: bool = ...): ...def is_string_array(values: np.ndarray, skipna: bool = ...): ...def is_float_array(values: np.ndarray): ...def is_integer_array(values: np.ndarray, skipna: bool = ...): ...def is_bool_array(values: np.ndarray, skipna: bool = ...): ...def fast_multiget( mapping: dict, keys: np.ndarray, # object[:] default=...,) -> np.ndarray: ...def fast_unique_multiple_list_gen(gen: Generator, sort: bool = ...) -> list: ...def fast_unique_multiple_list(lists: list, sort: bool | None = ...) -> list: ...def map_infer( arr: np.ndarray, f: Callable[[Any], Any], convert: bool = ..., ignore_na: bool = ...,) -> np.ndarray: ...@overloaddef maybe_convert_objects( objects: npt.NDArray[np.object_], *, try_float: bool = ..., safe: bool = ..., convert_numeric: bool = ..., convert_non_numeric: Literal[False] = ..., convert_to_nullable_dtype: Literal[False] = ..., dtype_if_all_nat: DtypeObj | None = ...,) -> npt.NDArray[np.object_ | np.number]: ...@overloaddef maybe_convert_objects( objects: npt.NDArray[np.object_], *, try_float: bool = ..., safe: bool = ..., convert_numeric: bool = ..., convert_non_numeric: bool = ..., convert_to_nullable_dtype: Literal[True] = ..., dtype_if_all_nat: DtypeObj | None = ...,) -> ArrayLike: ...@overloaddef maybe_convert_objects( objects: npt.NDArray[np.object_], *, try_float: bool = ..., safe: bool = ..., convert_numeric: bool = ..., convert_non_numeric: bool = ..., convert_to_nullable_dtype: bool = ..., dtype_if_all_nat: DtypeObj | None = ...,) -> ArrayLike: ...@overloaddef maybe_convert_numeric( values: npt.NDArray[np.object_], na_values: set, convert_empty: bool = ..., coerce_numeric: bool = ..., convert_to_masked_nullable: Literal[False] = ...,) -> tuple[np.ndarray, None]: ...@overloaddef maybe_convert_numeric( values: npt.NDArray[np.object_], na_values: set, convert_empty: bool = ..., coerce_numeric: bool = ..., *, convert_to_masked_nullable: Literal[True],) -> tuple[np.ndarray, np.ndarray]: ...
# TODO: restrict `arr`?def ensure_string_array( arr, na_value: object = ..., convert_na_value: bool = ..., copy: bool = ..., skipna: bool = ...,) -> npt.NDArray[np.object_]: ...def convert_nans_to_NA( arr: npt.NDArray[np.object_],) -> npt.NDArray[np.object_]: ...def fast_zip(ndarrays: list) -> npt.NDArray[np.object_]: ...
# TODO: can we be more specific about rows?def to_object_array_tuples(rows: object) -> ndarray_obj_2d: ...def tuples_to_object_array( tuples: npt.NDArray[np.object_],) -> ndarray_obj_2d: ...
# TODO: can we be more specific about rows?def to_object_array(rows: object, min_width: int = ...) -> ndarray_obj_2d: ...def dicts_to_array(dicts: list, columns: list) -> ndarray_obj_2d: ...def maybe_booleans_to_slice( mask: npt.NDArray[np.uint8],) -> slice | npt.NDArray[np.uint8]: ...def maybe_indices_to_slice( indices: npt.NDArray[np.intp], max_len: int,) -> slice | npt.NDArray[np.intp]: ...def is_all_arraylike(obj: list) -> bool: ...
# -----------------------------------------------------------------# Functions which in reality take memoryviews
def memory_usage_of_objects(arr: np.ndarray) -> int: ... # object[:] # np.int64def map_infer_mask( arr: np.ndarray, f: Callable[[Any], Any], mask: np.ndarray, # const uint8_t[:] convert: bool = ..., na_value: Any = ..., dtype: np.dtype = ...,) -> np.ndarray: ...def indices_fast( index: npt.NDArray[np.intp], labels: np.ndarray, # const int64_t[:] keys: list, sorted_labels: list[npt.NDArray[np.int64]],) -> dict[Hashable, npt.NDArray[np.intp]]: ...def generate_slices( labels: np.ndarray, ngroups: int # const intp_t[:]) -> tuple[npt.NDArray[np.int64], npt.NDArray[np.int64]]: ...def count_level_2d( mask: np.ndarray, # ndarray[uint8_t, ndim=2, cast=True], labels: np.ndarray, # const intp_t[:] max_bin: int,) -> np.ndarray: ... # np.ndarray[np.int64, ndim=2]def get_level_sorter( codes: np.ndarray, # const int64_t[:] starts: np.ndarray, # const intp_t[:]) -> np.ndarray: ... # np.ndarray[np.intp, ndim=1]def generate_bins_dt64( values: npt.NDArray[np.int64], binner: np.ndarray, # const int64_t[:] closed: object = ..., hasnans: bool = ...,) -> np.ndarray: ... # np.ndarray[np.int64, ndim=1]def array_equivalent_object( left: npt.NDArray[np.object_], right: npt.NDArray[np.object_],) -> bool: ...def has_infs(arr: np.ndarray) -> bool: ... # const floating[:]def has_only_ints_or_nan(arr: np.ndarray) -> bool: ... # const floating[:]def get_reverse_indexer( indexer: np.ndarray, # const intp_t[:] length: int,) -> npt.NDArray[np.intp]: ...def is_bool_list(obj: list) -> bool: ...def dtypes_all_equal(types: list[DtypeObj]) -> bool: ...def is_range_indexer( left: np.ndarray, n: int # np.ndarray[np.int64, ndim=1]) -> bool: ...12345678910111213141516import numpy as npfrom numpy import typing as npt
class NAType: def __new__(cls, *args, **kwargs): ...
NA: NAType
def is_matching_na( left: object, right: object, nan_matches_none: bool = ...) -> bool: ...def isposinf_scalar(val: object) -> bool: ...def isneginf_scalar(val: object) -> bool: ...def checknull(val: object, inf_as_na: bool = ...) -> bool: ...def isnaobj(arr: np.ndarray, inf_as_na: bool = ...) -> npt.NDArray[np.bool_]: ...def is_numeric_na(values: np.ndarray) -> npt.NDArray[np.bool_]: ...123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051from typing import ( Any, Callable, Iterable, Literal, TypeAlias, overload,)
import numpy as np
from pandas._typing import npt
_BinOp: TypeAlias = Callable[[Any, Any], Any]_BoolOp: TypeAlias = Callable[[Any, Any], bool]
def scalar_compare( values: np.ndarray, # object[:] val: object, op: _BoolOp, # {operator.eq, operator.ne, ...}) -> npt.NDArray[np.bool_]: ...def vec_compare( left: npt.NDArray[np.object_], right: npt.NDArray[np.object_], op: _BoolOp, # {operator.eq, operator.ne, ...}) -> npt.NDArray[np.bool_]: ...def scalar_binop( values: np.ndarray, # object[:] val: object, op: _BinOp, # binary operator) -> np.ndarray: ...def vec_binop( left: np.ndarray, # object[:] right: np.ndarray, # object[:] op: _BinOp, # binary operator) -> np.ndarray: ...@overloaddef maybe_convert_bool( arr: npt.NDArray[np.object_], true_values: Iterable | None = None, false_values: Iterable | None = None, convert_to_masked_nullable: Literal[False] = ...,) -> tuple[np.ndarray, None]: ...@overloaddef maybe_convert_bool( arr: npt.NDArray[np.object_], true_values: Iterable = ..., false_values: Iterable = ..., *, convert_to_masked_nullable: Literal[True],) -> tuple[np.ndarray, np.ndarray]: ...12345import numpy as np
def maybe_dispatch_ufunc_to_dunder_op( self, ufunc: np.ufunc, method: str, *inputs, **kwargs): ...1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677from typing import ( Hashable, Literal,)
import numpy as np
from pandas._typing import ( ArrayLike, Dtype, npt,)
STR_NA_VALUES: set[str]DEFAULT_BUFFER_HEURISTIC: int
def sanitize_objects( values: npt.NDArray[np.object_], na_values: set,) -> int: ...
class TextReader: unnamed_cols: set[str] table_width: int # int64_t leading_cols: int # int64_t header: list[list[int]] # non-negative integers def __init__( self, source, delimiter: bytes | str = ..., # single-character only header=..., header_start: int = ..., # int64_t header_end: int = ..., # uint64_t index_col=..., names=..., tokenize_chunksize: int = ..., # int64_t delim_whitespace: bool = ..., converters=..., skipinitialspace: bool = ..., escapechar: bytes | str | None = ..., # single-character only doublequote: bool = ..., quotechar: str | bytes | None = ..., # at most 1 character quoting: int = ..., lineterminator: bytes | str | None = ..., # at most 1 character comment=..., decimal: bytes | str = ..., # single-character only thousands: bytes | str | None = ..., # single-character only dtype: Dtype | dict[Hashable, Dtype] = ..., usecols=..., error_bad_lines: bool = ..., warn_bad_lines: bool = ..., na_filter: bool = ..., na_values=..., na_fvalues=..., keep_default_na: bool = ..., true_values=..., false_values=..., allow_leading_cols: bool = ..., skiprows=..., skipfooter: int = ..., # int64_t verbose: bool = ..., float_precision: Literal["round_trip", "legacy", "high"] | None = ..., skip_blank_lines: bool = ..., encoding_errors: bytes | str = ..., ) -> None: ... def set_noconvert(self, i: int) -> None: ... def remove_noconvert(self, i: int) -> None: ... def close(self) -> None: ... def read(self, rows: int | None = ...) -> dict[int, ArrayLike]: ... def read_low_memory(self, rows: int | None) -> list[dict[int, ArrayLike]]: ...
# _maybe_upcast, na_values are only exposed for testingna_values: dict
def _maybe_upcast( arr, use_dtype_backend: bool = ..., dtype_backend: str = ...) -> np.ndarray: ...123456789101112131415161718192021222324252627from typing import ( Sequence, overload,)
from pandas._typing import ( AnyArrayLike, DataFrame, Index, Series,)
# note: this is a lie to make type checkers happy (they special# case property). cache_readonly uses attribute names similar to# property (fget) but it does not provide fset and fdel.cache_readonly = property
class AxisProperty: axis: int def __init__(self, axis: int = ..., doc: str = ...) -> None: ... @overload def __get__(self, obj: DataFrame | Series, type) -> Index: ... @overload def __get__(self, obj: None, type) -> AxisProperty: ... def __set__( self, obj: DataFrame | Series, value: AnyArrayLike | Sequence ) -> None: ...12345678910111213141516import numpy as np
from pandas._typing import npt
def unstack( values: np.ndarray, # reshape_t[:, :] mask: np.ndarray, # const uint8_t[:] stride: int, length: int, width: int, new_values: np.ndarray, # reshape_t[:, :] new_mask: np.ndarray, # uint8_t[:, :]) -> None: ...def explode( values: npt.NDArray[np.object_],) -> tuple[npt.NDArray[np.object_], npt.NDArray[np.int64]]: ...1234567from pandas.io.sas.sas7bdat import SAS7BDATReader
class Parser: def __init__(self, parser: SAS7BDATReader) -> None: ... def read(self, nrows: int) -> None: ...
def get_subheader_index(signature: bytes) -> int: ...123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051from typing import Sequence
import numpy as np
from pandas._typing import ( Self, npt,)
class SparseIndex: length: int npoints: int def __init__(self) -> None: ... @property def ngaps(self) -> int: ... @property def nbytes(self) -> int: ... @property def indices(self) -> npt.NDArray[np.int32]: ... def equals(self, other) -> bool: ... def lookup(self, index: int) -> np.int32: ... def lookup_array(self, indexer: npt.NDArray[np.int32]) -> npt.NDArray[np.int32]: ... def to_int_index(self) -> IntIndex: ... def to_block_index(self) -> BlockIndex: ... def intersect(self, y_: SparseIndex) -> Self: ... def make_union(self, y_: SparseIndex) -> Self: ...
class IntIndex(SparseIndex): indices: npt.NDArray[np.int32] def __init__( self, length: int, indices: Sequence[int], check_integrity: bool = ... ) -> None: ...
class BlockIndex(SparseIndex): nblocks: int blocs: np.ndarray blengths: np.ndarray def __init__( self, length: int, blocs: np.ndarray, blengths: np.ndarray ) -> None: ...
# Override to have correct parameters def intersect(self, other: SparseIndex) -> Self: ... def make_union(self, y: SparseIndex) -> Self: ...
def make_mask_object_ndarray( arr: npt.NDArray[np.object_], fill_value) -> npt.NDArray[np.bool_]: ...def get_blocks( indices: npt.NDArray[np.int32],) -> tuple[npt.NDArray[np.int32], npt.NDArray[np.int32]]: ...123456789101112def assert_dict_equal(a, b, compare_keys: bool = ...): ...def assert_almost_equal( a, b, rtol: float = ..., atol: float = ..., check_dtype: bool = ..., obj=..., lobj=..., robj=..., index_values=...,): ...12345678910111213141516171819202122232425262728293031323334353637from datetime import tzinfo
import numpy as np
from pandas._typing import npt
def format_array_from_datetime( values: npt.NDArray[np.int64], tz: tzinfo | None = ..., format: str | None = ..., na_rep: str | float = ..., reso: int = ..., # NPY_DATETIMEUNIT) -> npt.NDArray[np.object_]: ...def array_with_unit_to_datetime( values: npt.NDArray[np.object_], unit: str, errors: str = ...,) -> tuple[np.ndarray, tzinfo | None]: ...def first_non_null(values: np.ndarray) -> int: ...def array_to_datetime( values: npt.NDArray[np.object_], errors: str = ..., dayfirst: bool = ..., yearfirst: bool = ..., utc: bool = ..., creso: int = ...,) -> tuple[np.ndarray, tzinfo | None]: ...
# returned ndarray may be object dtype or datetime64[ns]
def array_to_datetime_with_tz( values: npt.NDArray[np.object_], tz: tzinfo, dayfirst: bool, yearfirst: bool, creso: int,) -> npt.NDArray[np.int64]: ...1234567891011121314151617181920import numpy as np
from pandas._typing import ArrayLike
def write_csv_rows( data: list[ArrayLike], data_index: np.ndarray, nlevels: int, cols: np.ndarray, writer: object, # _csv.writer) -> None: ...def convert_json_to_lines(arr: str) -> str: ...def max_len_string_array( arr: np.ndarray, # pandas_string[:]) -> int: ...def word_len(val: object) -> int: ...def string_array_replace_from_nan_rep( arr: np.ndarray, # np.ndarray[object, ndim=1] nan_rep: object,) -> None: ...123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340"""
accessor.py contains base classes for implementing accessor propertiesthat can be mixed into or pinned onto other pandas classes.
"""from __future__ import annotations
from typing import ( Callable, final,)import warnings
from pandas.util._decorators import docfrom pandas.util._exceptions import find_stack_level
class DirNamesMixin: _accessors: set[str] = set() _hidden_attrs: frozenset[str] = frozenset()
@final def _dir_deletions(self) -> set[str]: """ Delete unwanted __dir__ for this object. """ return self._accessors | self._hidden_attrs
def _dir_additions(self) -> set[str]: """ Add additional __dir__ for this object. """ return {accessor for accessor in self._accessors if hasattr(self, accessor)}
def __dir__(self) -> list[str]: """ Provide method name lookup and completion.
Notes ----- Only provide 'public' methods. """ rv = set(super().__dir__()) rv = (rv - self._dir_deletions()) | self._dir_additions() return sorted(rv)
class PandasDelegate: """ Abstract base class for delegating methods/properties. """
def _delegate_property_get(self, name: str, *args, **kwargs): raise TypeError(f"You cannot access the property {name}")
def _delegate_property_set(self, name: str, value, *args, **kwargs): raise TypeError(f"The property {name} cannot be set")
def _delegate_method(self, name: str, *args, **kwargs): raise TypeError(f"You cannot call method {name}")
@classmethod def _add_delegate_accessors( cls, delegate, accessors: list[str], typ: str, overwrite: bool = False, accessor_mapping: Callable[[str], str] = lambda x: x, raise_on_missing: bool = True, ) -> None: """ Add accessors to cls from the delegate class.
Parameters ---------- cls Class to add the methods/properties to. delegate Class to get methods/properties and doc-strings. accessors : list of str List of accessors to add. typ : {'property', 'method'} overwrite : bool, default False Overwrite the method/property in the target class if it exists. accessor_mapping: Callable, default lambda x: x Callable to map the delegate's function to the cls' function. raise_on_missing: bool, default True Raise if an accessor does not exist on delegate. False skips the missing accessor. """
def _create_delegator_property(name: str): def _getter(self): return self._delegate_property_get(name)
def _setter(self, new_values): return self._delegate_property_set(name, new_values)
_getter.__name__ = name _setter.__name__ = name
return property( fget=_getter, fset=_setter, doc=getattr(delegate, accessor_mapping(name)).__doc__, )
def _create_delegator_method(name: str): def f(self, *args, **kwargs): return self._delegate_method(name, *args, **kwargs)
f.__name__ = name f.__doc__ = getattr(delegate, accessor_mapping(name)).__doc__
return f
for name in accessors: if ( not raise_on_missing and getattr(delegate, accessor_mapping(name), None) is None ): continue
if typ == "property": f = _create_delegator_property(name) else: f = _create_delegator_method(name)
# don't overwrite existing methods/properties if overwrite or not hasattr(cls, name): setattr(cls, name, f)
def delegate_names( delegate, accessors: list[str], typ: str, overwrite: bool = False, accessor_mapping: Callable[[str], str] = lambda x: x, raise_on_missing: bool = True,): """ Add delegated names to a class using a class decorator. This provides an alternative usage to directly calling `_add_delegate_accessors` below a class definition.
Parameters ---------- delegate : object The class to get methods/properties & doc-strings. accessors : Sequence[str] List of accessor to add. typ : {'property', 'method'} overwrite : bool, default False Overwrite the method/property in the target class if it exists. accessor_mapping: Callable, default lambda x: x Callable to map the delegate's function to the cls' function. raise_on_missing: bool, default True Raise if an accessor does not exist on delegate. False skips the missing accessor.
Returns ------- callable A class decorator.
Examples -------- @delegate_names(Categorical, ["categories", "ordered"], "property") class CategoricalAccessor(PandasDelegate): [...] """
def add_delegate_accessors(cls): cls._add_delegate_accessors( delegate, accessors, typ, overwrite=overwrite, accessor_mapping=accessor_mapping, raise_on_missing=raise_on_missing, ) return cls
return add_delegate_accessors
# Ported with modifications from xarray; licence at LICENSES/XARRAY_LICENSE# https://github.com/pydata/xarray/blob/master/xarray/core/extensions.py# 1. We don't need to catch and re-raise AttributeErrors as RuntimeErrors# 2. We use a UserWarning instead of a custom Warning
class CachedAccessor: """ Custom property-like object.
A descriptor for caching accessors.
Parameters ---------- name : str Namespace that will be accessed under, e.g. ``df.foo``. accessor : cls Class with the extension methods.
Notes ----- For accessor, The class's __init__ method assumes that one of ``Series``, ``DataFrame`` or ``Index`` as the single argument ``data``. """
def __init__(self, name: str, accessor) -> None: self._name = name self._accessor = accessor
def __get__(self, obj, cls): if obj is None: # we're accessing the attribute of the class, i.e., Dataset.geo return self._accessor accessor_obj = self._accessor(obj) # Replace the property with the accessor object. Inspired by: # https://www.pydanny.com/cached-property.html # We need to use object.__setattr__ because we overwrite __setattr__ on # NDFrame object.__setattr__(obj, self._name, accessor_obj) return accessor_obj
@doc(klass="", others="")def _register_accessor(name: str, cls): """ Register a custom accessor on {klass} objects.
Parameters ---------- name : str Name under which the accessor should be registered. A warning is issued if this name conflicts with a preexisting attribute.
Returns ------- callable A class decorator.
See Also -------- register_dataframe_accessor : Register a custom accessor on DataFrame objects. register_series_accessor : Register a custom accessor on Series objects. register_index_accessor : Register a custom accessor on Index objects.
Notes ----- When accessed, your accessor will be initialized with the pandas object the user is interacting with. So the signature must be
.. code-block:: python
def __init__(self, pandas_object): # noqa: E999 ...
For consistency with pandas methods, you should raise an ``AttributeError`` if the data passed to your accessor has an incorrect dtype.
>>> pd.Series(['a', 'b']).dt Traceback (most recent call last): ... AttributeError: Can only use .dt accessor with datetimelike values
Examples -------- In your library code::
import pandas as pd
@pd.api.extensions.register_dataframe_accessor("geo") class GeoAccessor: def __init__(self, pandas_obj): self._obj = pandas_obj
@property def center(self): # return the geographic center point of this DataFrame lat = self._obj.latitude lon = self._obj.longitude return (float(lon.mean()), float(lat.mean()))
def plot(self): # plot this array's data on a map, e.g., using Cartopy pass
Back in an interactive IPython session:
.. code-block:: ipython
In [1]: ds = pd.DataFrame({{"longitude": np.linspace(0, 10), ...: "latitude": np.linspace(0, 20)}}) In [2]: ds.geo.center Out[2]: (5.0, 10.0) In [3]: ds.geo.plot() # plots data on a map """
def decorator(accessor): if hasattr(cls, name): warnings.warn( f"registration of accessor {repr(accessor)} under name " f"{repr(name)} for type {repr(cls)} is overriding a preexisting " f"attribute with the same name.", UserWarning, stacklevel=find_stack_level(), ) setattr(cls, name, CachedAccessor(name, accessor)) cls._accessors.add(name) return accessor
return decorator
@doc(_register_accessor, klass="DataFrame")def register_dataframe_accessor(name: str): from pandas import DataFrame
return _register_accessor(name, DataFrame)
@doc(_register_accessor, klass="Series")def register_series_accessor(name: str): from pandas import Series
return _register_accessor(name, Series)
@doc(_register_accessor, klass="Index")def register_index_accessor(name: str): from pandas import Index
return _register_accessor(name, Index)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747"""Generic data algorithms. This module is experimental at the moment and notintended for public consumption"""from __future__ import annotations
import decimalimport operatorfrom textwrap import dedentfrom typing import ( TYPE_CHECKING, Literal, cast,)import warnings
import numpy as np
from pandas._libs import ( algos, hashtable as htable, iNaT, lib,)from pandas._typing import ( AnyArrayLike, ArrayLike, AxisInt, DtypeObj, TakeIndexer, npt,)from pandas.util._decorators import docfrom pandas.util._exceptions import find_stack_level
from pandas.core.dtypes.cast import ( construct_1d_object_array_from_listlike, np_find_common_type,)from pandas.core.dtypes.common import ( ensure_float64, ensure_object, ensure_platform_int, is_array_like, is_bool_dtype, is_complex_dtype, is_dict_like, is_extension_array_dtype, is_float_dtype, is_integer, is_integer_dtype, is_list_like, is_object_dtype, is_signed_integer_dtype, needs_i8_conversion,)from pandas.core.dtypes.concat import concat_compatfrom pandas.core.dtypes.dtypes import ( BaseMaskedDtype, CategoricalDtype, ExtensionDtype, NumpyEADtype,)from pandas.core.dtypes.generic import ( ABCDatetimeArray, ABCExtensionArray, ABCIndex, ABCMultiIndex, ABCSeries, ABCTimedeltaArray,)from pandas.core.dtypes.missing import ( isna, na_value_for_dtype,)
from pandas.core.array_algos.take import take_ndfrom pandas.core.construction import ( array as pd_array, ensure_wrapped_if_datetimelike, extract_array,)from pandas.core.indexers import validate_indices
if TYPE_CHECKING: from pandas._typing import ( ListLike, NumpySorter, NumpyValueArrayLike, )
from pandas import ( Categorical, Index, Series, ) from pandas.core.arrays import ( BaseMaskedArray, ExtensionArray, )
# --------------- ## dtype access ## --------------- #def _ensure_data(values: ArrayLike) -> np.ndarray: """ routine to ensure that our data is of the correct input dtype for lower-level routines
This will coerce: - ints -> int64 - uint -> uint64 - bool -> uint8 - datetimelike -> i8 - datetime64tz -> i8 (in local tz) - categorical -> codes
Parameters ---------- values : np.ndarray or ExtensionArray
Returns ------- np.ndarray """
if not isinstance(values, ABCMultiIndex): # extract_array would raise values = extract_array(values, extract_numpy=True)
if is_object_dtype(values.dtype): return ensure_object(np.asarray(values))
elif isinstance(values.dtype, BaseMaskedDtype): # i.e. BooleanArray, FloatingArray, IntegerArray values = cast("BaseMaskedArray", values) if not values._hasna: # No pd.NAs -> We can avoid an object-dtype cast (and copy) GH#41816 # recurse to avoid re-implementing logic for eg bool->uint8 return _ensure_data(values._data) return np.asarray(values)
elif isinstance(values.dtype, CategoricalDtype): # NB: cases that go through here should NOT be using _reconstruct_data # on the back-end. values = cast("Categorical", values) return values.codes
elif is_bool_dtype(values.dtype): if isinstance(values, np.ndarray): # i.e. actually dtype == np.dtype("bool") return np.asarray(values).view("uint8") else: # e.g. Sparse[bool, False] # TODO: no test cases get here return np.asarray(values).astype("uint8", copy=False)
elif is_integer_dtype(values.dtype): return np.asarray(values)
elif is_float_dtype(values.dtype): # Note: checking `values.dtype == "float128"` raises on Windows and 32bit # error: Item "ExtensionDtype" of "Union[Any, ExtensionDtype, dtype[Any]]" # has no attribute "itemsize" if values.dtype.itemsize in [2, 12, 16]: # type: ignore[union-attr] # we dont (yet) have float128 hashtable support return ensure_float64(values) return np.asarray(values)
elif is_complex_dtype(values.dtype): return cast(np.ndarray, values)
# datetimelike elif needs_i8_conversion(values.dtype): npvalues = values.view("i8") npvalues = cast(np.ndarray, npvalues) return npvalues
# we have failed, return object values = np.asarray(values, dtype=object) return ensure_object(values)
def _reconstruct_data( values: ArrayLike, dtype: DtypeObj, original: AnyArrayLike) -> ArrayLike: """ reverse of _ensure_data
Parameters ---------- values : np.ndarray or ExtensionArray dtype : np.dtype or ExtensionDtype original : AnyArrayLike
Returns ------- ExtensionArray or np.ndarray """ if isinstance(values, ABCExtensionArray) and values.dtype == dtype: # Catch DatetimeArray/TimedeltaArray return values
if not isinstance(dtype, np.dtype): # i.e. ExtensionDtype; note we have ruled out above the possibility # that values.dtype == dtype cls = dtype.construct_array_type()
values = cls._from_sequence(values, dtype=dtype)
else: values = values.astype(dtype, copy=False)
return values
def _ensure_arraylike(values, func_name: str) -> ArrayLike: """ ensure that we are arraylike if not already """ if not isinstance(values, (ABCIndex, ABCSeries, ABCExtensionArray, np.ndarray)): # GH#52986 if func_name != "isin-targets": # Make an exception for the comps argument in isin. warnings.warn( f"{func_name} with argument that is not not a Series, Index, " "ExtensionArray, or np.ndarray is deprecated and will raise in a " "future version.", FutureWarning, stacklevel=find_stack_level(), )
inferred = lib.infer_dtype(values, skipna=False) if inferred in ["mixed", "string", "mixed-integer"]: # "mixed-integer" to ensure we do not cast ["ss", 42] to str GH#22160 if isinstance(values, tuple): values = list(values) values = construct_1d_object_array_from_listlike(values) else: values = np.asarray(values) return values
_hashtables = { "complex128": htable.Complex128HashTable, "complex64": htable.Complex64HashTable, "float64": htable.Float64HashTable, "float32": htable.Float32HashTable, "uint64": htable.UInt64HashTable, "uint32": htable.UInt32HashTable, "uint16": htable.UInt16HashTable, "uint8": htable.UInt8HashTable, "int64": htable.Int64HashTable, "int32": htable.Int32HashTable, "int16": htable.Int16HashTable, "int8": htable.Int8HashTable, "string": htable.StringHashTable, "object": htable.PyObjectHashTable,}
def _get_hashtable_algo(values: np.ndarray): """ Parameters ---------- values : np.ndarray
Returns ------- htable : HashTable subclass values : ndarray """ values = _ensure_data(values)
ndtype = _check_object_for_strings(values) hashtable = _hashtables[ndtype] return hashtable, values
def _check_object_for_strings(values: np.ndarray) -> str: """ Check if we can use string hashtable instead of object hashtable.
Parameters ---------- values : ndarray
Returns ------- str """ ndtype = values.dtype.name if ndtype == "object": # it's cheaper to use a String Hash Table than Object; we infer # including nulls because that is the only difference between # StringHashTable and ObjectHashtable if lib.is_string_array(values, skipna=False): ndtype = "string" return ndtype
# --------------- ## top-level algos ## --------------- #
def unique(values): """ Return unique values based on a hash table.
Uniques are returned in order of appearance. This does NOT sort.
Significantly faster than numpy.unique for long enough sequences. Includes NA values.
Parameters ---------- values : 1d array-like
Returns ------- numpy.ndarray or ExtensionArray
The return can be:
* Index : when the input is an Index * Categorical : when the input is a Categorical dtype * ndarray : when the input is a Series/ndarray
Return numpy.ndarray or ExtensionArray.
See Also -------- Index.unique : Return unique values from an Index. Series.unique : Return unique values of Series object.
Examples -------- >>> pd.unique(pd.Series([2, 1, 3, 3])) array([2, 1, 3])
>>> pd.unique(pd.Series([2] + [1] * 5)) array([2, 1])
>>> pd.unique(pd.Series([pd.Timestamp("20160101"), pd.Timestamp("20160101")])) array(['2016-01-01T00:00:00.000000000'], dtype='datetime64[ns]')
>>> pd.unique( ... pd.Series( ... [ ... pd.Timestamp("20160101", tz="US/Eastern"), ... pd.Timestamp("20160101", tz="US/Eastern"), ... ] ... ) ... ) <DatetimeArray> ['2016-01-01 00:00:00-05:00'] Length: 1, dtype: datetime64[ns, US/Eastern]
>>> pd.unique( ... pd.Index( ... [ ... pd.Timestamp("20160101", tz="US/Eastern"), ... pd.Timestamp("20160101", tz="US/Eastern"), ... ] ... ) ... ) DatetimeIndex(['2016-01-01 00:00:00-05:00'], dtype='datetime64[ns, US/Eastern]', freq=None)
>>> pd.unique(np.array(list("baabc"), dtype="O")) array(['b', 'a', 'c'], dtype=object)
An unordered Categorical will return categories in the order of appearance.
>>> pd.unique(pd.Series(pd.Categorical(list("baabc")))) ['b', 'a', 'c'] Categories (3, object): ['a', 'b', 'c']
>>> pd.unique(pd.Series(pd.Categorical(list("baabc"), categories=list("abc")))) ['b', 'a', 'c'] Categories (3, object): ['a', 'b', 'c']
An ordered Categorical preserves the category ordering.
>>> pd.unique( ... pd.Series( ... pd.Categorical(list("baabc"), categories=list("abc"), ordered=True) ... ) ... ) ['b', 'a', 'c'] Categories (3, object): ['a' < 'b' < 'c']
An array of tuples
>>> pd.unique(pd.Series([("a", "b"), ("b", "a"), ("a", "c"), ("b", "a")]).values) array([('a', 'b'), ('b', 'a'), ('a', 'c')], dtype=object) """ return unique_with_mask(values)
def nunique_ints(values: ArrayLike) -> int: """ Return the number of unique values for integer array-likes.
Significantly faster than pandas.unique for long enough sequences. No checks are done to ensure input is integral.
Parameters ---------- values : 1d array-like
Returns ------- int : The number of unique values in ``values`` """ if len(values) == 0: return 0 values = _ensure_data(values) # bincount requires intp result = (np.bincount(values.ravel().astype("intp")) != 0).sum() return result
def unique_with_mask(values, mask: npt.NDArray[np.bool_] | None = None): """See algorithms.unique for docs. Takes a mask for masked arrays.""" values = _ensure_arraylike(values, func_name="unique")
if isinstance(values.dtype, ExtensionDtype): # Dispatch to extension dtype's unique. return values.unique()
original = values hashtable, values = _get_hashtable_algo(values)
table = hashtable(len(values)) if mask is None: uniques = table.unique(values) uniques = _reconstruct_data(uniques, original.dtype, original) return uniques
else: uniques, mask = table.unique(values, mask=mask) uniques = _reconstruct_data(uniques, original.dtype, original) assert mask is not None # for mypy return uniques, mask.astype("bool")
unique1d = unique
_MINIMUM_COMP_ARR_LEN = 1_000_000
def isin(comps: ListLike, values: ListLike) -> npt.NDArray[np.bool_]: """ Compute the isin boolean array.
Parameters ---------- comps : list-like values : list-like
Returns ------- ndarray[bool] Same length as `comps`. """ if not is_list_like(comps): raise TypeError( "only list-like objects are allowed to be passed " f"to isin(), you passed a `{type(comps).__name__}`" ) if not is_list_like(values): raise TypeError( "only list-like objects are allowed to be passed " f"to isin(), you passed a `{type(values).__name__}`" )
if not isinstance(values, (ABCIndex, ABCSeries, ABCExtensionArray, np.ndarray)): orig_values = list(values) values = _ensure_arraylike(orig_values, func_name="isin-targets")
if ( len(values) > 0 and values.dtype.kind in "iufcb" and not is_signed_integer_dtype(comps) ): # GH#46485 Use object to avoid upcast to float64 later # TODO: Share with _find_common_type_compat values = construct_1d_object_array_from_listlike(orig_values)
elif isinstance(values, ABCMultiIndex): # Avoid raising in extract_array values = np.array(values) else: values = extract_array(values, extract_numpy=True, extract_range=True)
comps_array = _ensure_arraylike(comps, func_name="isin") comps_array = extract_array(comps_array, extract_numpy=True) if not isinstance(comps_array, np.ndarray): # i.e. Extension Array return comps_array.isin(values)
elif needs_i8_conversion(comps_array.dtype): # Dispatch to DatetimeLikeArrayMixin.isin return pd_array(comps_array).isin(values) elif needs_i8_conversion(values.dtype) and not is_object_dtype(comps_array.dtype): # e.g. comps_array are integers and values are datetime64s return np.zeros(comps_array.shape, dtype=bool) # TODO: not quite right ... Sparse/Categorical elif needs_i8_conversion(values.dtype): return isin(comps_array, values.astype(object))
elif isinstance(values.dtype, ExtensionDtype): return isin(np.asarray(comps_array), np.asarray(values))
# GH16012 # Ensure np.isin doesn't get object types or it *may* throw an exception # Albeit hashmap has O(1) look-up (vs. O(logn) in sorted array), # isin is faster for small sizes if ( len(comps_array) > _MINIMUM_COMP_ARR_LEN and len(values) <= 26 and comps_array.dtype != object ): # If the values include nan we need to check for nan explicitly # since np.nan it not equal to np.nan if isna(values).any():
def f(c, v): return np.logical_or(np.isin(c, v).ravel(), np.isnan(c))
else: f = lambda a, b: np.isin(a, b).ravel()
else: common = np_find_common_type(values.dtype, comps_array.dtype) values = values.astype(common, copy=False) comps_array = comps_array.astype(common, copy=False) f = htable.ismember
return f(comps_array, values)
def factorize_array( values: np.ndarray, use_na_sentinel: bool = True, size_hint: int | None = None, na_value: object = None, mask: npt.NDArray[np.bool_] | None = None,) -> tuple[npt.NDArray[np.intp], np.ndarray]: """ Factorize a numpy array to codes and uniques.
This doesn't do any coercion of types or unboxing before factorization.
Parameters ---------- values : ndarray use_na_sentinel : bool, default True If True, the sentinel -1 will be used for NaN values. If False, NaN values will be encoded as non-negative integers and will not drop the NaN from the uniques of the values. size_hint : int, optional Passed through to the hashtable's 'get_labels' method na_value : object, optional A value in `values` to consider missing. Note: only use this parameter when you know that you don't have any values pandas would consider missing in the array (NaN for float data, iNaT for datetimes, etc.). mask : ndarray[bool], optional If not None, the mask is used as indicator for missing values (True = missing, False = valid) instead of `na_value` or condition "val != val".
Returns ------- codes : ndarray[np.intp] uniques : ndarray """ original = values if values.dtype.kind in "mM": # _get_hashtable_algo will cast dt64/td64 to i8 via _ensure_data, so we # need to do the same to na_value. We are assuming here that the passed # na_value is an appropriately-typed NaT. # e.g. test_where_datetimelike_categorical na_value = iNaT
hash_klass, values = _get_hashtable_algo(values)
table = hash_klass(size_hint or len(values)) uniques, codes = table.factorize( values, na_sentinel=-1, na_value=na_value, mask=mask, ignore_na=use_na_sentinel, )
# re-cast e.g. i8->dt64/td64, uint8->bool uniques = _reconstruct_data(uniques, original.dtype, original)
codes = ensure_platform_int(codes) return codes, uniques
@doc( values=dedent( """\ values : sequence A 1-D sequence. Sequences that aren't pandas objects are coerced to ndarrays before factorization. """ ), sort=dedent( """\ sort : bool, default False Sort `uniques` and shuffle `codes` to maintain the relationship. """ ), size_hint=dedent( """\ size_hint : int, optional Hint to the hashtable sizer. """ ),)def factorize( values, sort: bool = False, use_na_sentinel: bool = True, size_hint: int | None = None,) -> tuple[np.ndarray, np.ndarray | Index]: """ Encode the object as an enumerated type or categorical variable.
This method is useful for obtaining a numeric representation of an array when all that matters is identifying distinct values. `factorize` is available as both a top-level function :func:`pandas.factorize`, and as a method :meth:`Series.factorize` and :meth:`Index.factorize`.
Parameters ---------- {values}{sort} use_na_sentinel : bool, default True If True, the sentinel -1 will be used for NaN values. If False, NaN values will be encoded as non-negative integers and will not drop the NaN from the uniques of the values.
.. versionadded:: 1.5.0 {size_hint}\
Returns ------- codes : ndarray An integer ndarray that's an indexer into `uniques`. ``uniques.take(codes)`` will have the same values as `values`. uniques : ndarray, Index, or Categorical The unique valid values. When `values` is Categorical, `uniques` is a Categorical. When `values` is some other pandas object, an `Index` is returned. Otherwise, a 1-D ndarray is returned.
.. note::
Even if there's a missing value in `values`, `uniques` will *not* contain an entry for it.
See Also -------- cut : Discretize continuous-valued array. unique : Find the unique value in an array.
Notes ----- Reference :ref:`the user guide <reshaping.factorize>` for more examples.
Examples -------- These examples all show factorize as a top-level method like ``pd.factorize(values)``. The results are identical for methods like :meth:`Series.factorize`.
>>> codes, uniques = pd.factorize(np.array(['b', 'b', 'a', 'c', 'b'], dtype="O")) >>> codes array([0, 0, 1, 2, 0]) >>> uniques array(['b', 'a', 'c'], dtype=object)
With ``sort=True``, the `uniques` will be sorted, and `codes` will be shuffled so that the relationship is the maintained.
>>> codes, uniques = pd.factorize(np.array(['b', 'b', 'a', 'c', 'b'], dtype="O"), ... sort=True) >>> codes array([1, 1, 0, 2, 1]) >>> uniques array(['a', 'b', 'c'], dtype=object)
When ``use_na_sentinel=True`` (the default), missing values are indicated in the `codes` with the sentinel value ``-1`` and missing values are not included in `uniques`.
>>> codes, uniques = pd.factorize(np.array(['b', None, 'a', 'c', 'b'], dtype="O")) >>> codes array([ 0, -1, 1, 2, 0]) >>> uniques array(['b', 'a', 'c'], dtype=object)
Thus far, we've only factorized lists (which are internally coerced to NumPy arrays). When factorizing pandas objects, the type of `uniques` will differ. For Categoricals, a `Categorical` is returned.
>>> cat = pd.Categorical(['a', 'a', 'c'], categories=['a', 'b', 'c']) >>> codes, uniques = pd.factorize(cat) >>> codes array([0, 0, 1]) >>> uniques ['a', 'c'] Categories (3, object): ['a', 'b', 'c']
Notice that ``'b'`` is in ``uniques.categories``, despite not being present in ``cat.values``.
For all other pandas objects, an Index of the appropriate type is returned.
>>> cat = pd.Series(['a', 'a', 'c']) >>> codes, uniques = pd.factorize(cat) >>> codes array([0, 0, 1]) >>> uniques Index(['a', 'c'], dtype='object')
If NaN is in the values, and we want to include NaN in the uniques of the values, it can be achieved by setting ``use_na_sentinel=False``.
>>> values = np.array([1, 2, 1, np.nan]) >>> codes, uniques = pd.factorize(values) # default: use_na_sentinel=True >>> codes array([ 0, 1, 0, -1]) >>> uniques array([1., 2.])
>>> codes, uniques = pd.factorize(values, use_na_sentinel=False) >>> codes array([0, 1, 0, 2]) >>> uniques array([ 1., 2., nan]) """ # Implementation notes: This method is responsible for 3 things # 1.) coercing data to array-like (ndarray, Index, extension array) # 2.) factorizing codes and uniques # 3.) Maybe boxing the uniques in an Index # # Step 2 is dispatched to extension types (like Categorical). They are # responsible only for factorization. All data coercion, sorting and boxing # should happen here. if isinstance(values, (ABCIndex, ABCSeries)): return values.factorize(sort=sort, use_na_sentinel=use_na_sentinel)
values = _ensure_arraylike(values, func_name="factorize") original = values
if ( isinstance(values, (ABCDatetimeArray, ABCTimedeltaArray)) and values.freq is not None ): # The presence of 'freq' means we can fast-path sorting and know there # aren't NAs codes, uniques = values.factorize(sort=sort) return codes, uniques
elif not isinstance(values, np.ndarray): # i.e. ExtensionArray codes, uniques = values.factorize(use_na_sentinel=use_na_sentinel)
else: values = np.asarray(values) # convert DTA/TDA/MultiIndex
if not use_na_sentinel and values.dtype == object: # factorize can now handle differentiating various types of null values. # These can only occur when the array has object dtype. # However, for backwards compatibility we only use the null for the # provided dtype. This may be revisited in the future, see GH#48476. null_mask = isna(values) if null_mask.any(): na_value = na_value_for_dtype(values.dtype, compat=False) # Don't modify (potentially user-provided) array values = np.where(null_mask, na_value, values)
codes, uniques = factorize_array( values, use_na_sentinel=use_na_sentinel, size_hint=size_hint, )
if sort and len(uniques) > 0: uniques, codes = safe_sort( uniques, codes, use_na_sentinel=use_na_sentinel, assume_unique=True, verify=False, )
uniques = _reconstruct_data(uniques, original.dtype, original)
return codes, uniques
def value_counts( values, sort: bool = True, ascending: bool = False, normalize: bool = False, bins=None, dropna: bool = True,) -> Series: """ Compute a histogram of the counts of non-null values.
Parameters ---------- values : ndarray (1-d) sort : bool, default True Sort by values ascending : bool, default False Sort in ascending order normalize: bool, default False If True then compute a relative histogram bins : integer, optional Rather than count values, group them into half-open bins, convenience for pd.cut, only works with numeric data dropna : bool, default True Don't include counts of NaN
Returns ------- Series """ warnings.warn( # GH#53493 "pandas.value_counts is deprecated and will be removed in a " "future version. Use pd.Series(obj).value_counts() instead.", FutureWarning, stacklevel=find_stack_level(), ) return value_counts_internal( values, sort=sort, ascending=ascending, normalize=normalize, bins=bins, dropna=dropna, )
def value_counts_internal( values, sort: bool = True, ascending: bool = False, normalize: bool = False, bins=None, dropna: bool = True,) -> Series: from pandas import ( Index, Series, )
index_name = getattr(values, "name", None) name = "proportion" if normalize else "count"
if bins is not None: from pandas.core.reshape.tile import cut
if isinstance(values, Series): values = values._values
try: ii = cut(values, bins, include_lowest=True) except TypeError as err: raise TypeError("bins argument only works with numeric data.") from err
# count, remove nulls (from the index), and but the bins result = ii.value_counts(dropna=dropna) result.name = name result = result[result.index.notna()] result.index = result.index.astype("interval") result = result.sort_index()
# if we are dropna and we have NO values if dropna and (result._values == 0).all(): result = result.iloc[0:0]
# normalizing is by len of all (regardless of dropna) counts = np.array([len(ii)])
else: if is_extension_array_dtype(values): # handle Categorical and sparse, result = Series(values, copy=False)._values.value_counts(dropna=dropna) result.name = name result.index.name = index_name counts = result._values if not isinstance(counts, np.ndarray): # e.g. ArrowExtensionArray counts = np.asarray(counts)
elif isinstance(values, ABCMultiIndex): # GH49558 levels = list(range(values.nlevels)) result = ( Series(index=values, name=name) .groupby(level=levels, dropna=dropna) .size() ) result.index.names = values.names counts = result._values
else: values = _ensure_arraylike(values, func_name="value_counts") keys, counts, _ = value_counts_arraylike(values, dropna) if keys.dtype == np.float16: keys = keys.astype(np.float32)
# For backwards compatibility, we let Index do its normal type # inference, _except_ for if if infers from object to bool. idx = Index(keys) if idx.dtype == bool and keys.dtype == object: idx = idx.astype(object) elif ( idx.dtype != keys.dtype # noqa: PLR1714 # # pylint: disable=R1714 and idx.dtype != "string[pyarrow_numpy]" ): warnings.warn( # GH#56161 "The behavior of value_counts with object-dtype is deprecated. " "In a future version, this will *not* perform dtype inference " "on the resulting index. To retain the old behavior, use " "`result.index = result.index.infer_objects()`", FutureWarning, stacklevel=find_stack_level(), ) idx.name = index_name
result = Series(counts, index=idx, name=name, copy=False)
if sort: result = result.sort_values(ascending=ascending)
if normalize: result = result / counts.sum()
return result
# Called once from SparseArray, otherwise could be privatedef value_counts_arraylike( values: np.ndarray, dropna: bool, mask: npt.NDArray[np.bool_] | None = None) -> tuple[ArrayLike, npt.NDArray[np.int64], int]: """ Parameters ---------- values : np.ndarray dropna : bool mask : np.ndarray[bool] or None, default None
Returns ------- uniques : np.ndarray counts : np.ndarray[np.int64] """ original = values values = _ensure_data(values)
keys, counts, na_counter = htable.value_count(values, dropna, mask=mask)
if needs_i8_conversion(original.dtype): # datetime, timedelta, or period
if dropna: mask = keys != iNaT keys, counts = keys[mask], counts[mask]
res_keys = _reconstruct_data(keys, original.dtype, original) return res_keys, counts, na_counter
def duplicated( values: ArrayLike, keep: Literal["first", "last", False] = "first", mask: npt.NDArray[np.bool_] | None = None,) -> npt.NDArray[np.bool_]: """ Return boolean ndarray denoting duplicate values.
Parameters ---------- values : np.ndarray or ExtensionArray Array over which to check for duplicate values. keep : {'first', 'last', False}, default 'first' - ``first`` : Mark duplicates as ``True`` except for the first occurrence. - ``last`` : Mark duplicates as ``True`` except for the last occurrence. - False : Mark all duplicates as ``True``. mask : ndarray[bool], optional array indicating which elements to exclude from checking
Returns ------- duplicated : ndarray[bool] """ values = _ensure_data(values) return htable.duplicated(values, keep=keep, mask=mask)
def mode( values: ArrayLike, dropna: bool = True, mask: npt.NDArray[np.bool_] | None = None) -> ArrayLike: """ Returns the mode(s) of an array.
Parameters ---------- values : array-like Array over which to check for duplicate values. dropna : bool, default True Don't consider counts of NaN/NaT.
Returns ------- np.ndarray or ExtensionArray """ values = _ensure_arraylike(values, func_name="mode") original = values
if needs_i8_conversion(values.dtype): # Got here with ndarray; dispatch to DatetimeArray/TimedeltaArray. values = ensure_wrapped_if_datetimelike(values) values = cast("ExtensionArray", values) return values._mode(dropna=dropna)
values = _ensure_data(values)
npresult, res_mask = htable.mode(values, dropna=dropna, mask=mask) if res_mask is not None: return npresult, res_mask # type: ignore[return-value]
try: npresult = np.sort(npresult) except TypeError as err: warnings.warn( f"Unable to sort modes: {err}", stacklevel=find_stack_level(), )
result = _reconstruct_data(npresult, original.dtype, original) return result
def rank( values: ArrayLike, axis: AxisInt = 0, method: str = "average", na_option: str = "keep", ascending: bool = True, pct: bool = False,) -> npt.NDArray[np.float64]: """ Rank the values along a given axis.
Parameters ---------- values : np.ndarray or ExtensionArray Array whose values will be ranked. The number of dimensions in this array must not exceed 2. axis : int, default 0 Axis over which to perform rankings. method : {'average', 'min', 'max', 'first', 'dense'}, default 'average' The method by which tiebreaks are broken during the ranking. na_option : {'keep', 'top'}, default 'keep' The method by which NaNs are placed in the ranking. - ``keep``: rank each NaN value with a NaN ranking - ``top``: replace each NaN with either +/- inf so that they there are ranked at the top ascending : bool, default True Whether or not the elements should be ranked in ascending order. pct : bool, default False Whether or not to the display the returned rankings in integer form (e.g. 1, 2, 3) or in percentile form (e.g. 0.333..., 0.666..., 1). """ is_datetimelike = needs_i8_conversion(values.dtype) values = _ensure_data(values)
if values.ndim == 1: ranks = algos.rank_1d( values, is_datetimelike=is_datetimelike, ties_method=method, ascending=ascending, na_option=na_option, pct=pct, ) elif values.ndim == 2: ranks = algos.rank_2d( values, axis=axis, is_datetimelike=is_datetimelike, ties_method=method, ascending=ascending, na_option=na_option, pct=pct, ) else: raise TypeError("Array with ndim > 2 are not supported.")
return ranks
# ---- ## take ## ---- #
def take( arr, indices: TakeIndexer, axis: AxisInt = 0, allow_fill: bool = False, fill_value=None,): """ Take elements from an array.
Parameters ---------- arr : array-like or scalar value Non array-likes (sequences/scalars without a dtype) are coerced to an ndarray.
.. deprecated:: 2.1.0 Passing an argument other than a numpy.ndarray, ExtensionArray, Index, or Series is deprecated.
indices : sequence of int or one-dimensional np.ndarray of int Indices to be taken. axis : int, default 0 The axis over which to select values. allow_fill : bool, default False How to handle negative values in `indices`.
* False: negative values in `indices` indicate positional indices from the right (the default). This is similar to :func:`numpy.take`.
* True: negative values in `indices` indicate missing values. These values are set to `fill_value`. Any other negative values raise a ``ValueError``.
fill_value : any, optional Fill value to use for NA-indices when `allow_fill` is True. This may be ``None``, in which case the default NA value for the type (``self.dtype.na_value``) is used.
For multi-dimensional `arr`, each *element* is filled with `fill_value`.
Returns ------- ndarray or ExtensionArray Same type as the input.
Raises ------ IndexError When `indices` is out of bounds for the array. ValueError When the indexer contains negative values other than ``-1`` and `allow_fill` is True.
Notes ----- When `allow_fill` is False, `indices` may be whatever dimensionality is accepted by NumPy for `arr`.
When `allow_fill` is True, `indices` should be 1-D.
See Also -------- numpy.take : Take elements from an array along an axis.
Examples -------- >>> import pandas as pd
With the default ``allow_fill=False``, negative numbers indicate positional indices from the right.
>>> pd.api.extensions.take(np.array([10, 20, 30]), [0, 0, -1]) array([10, 10, 30])
Setting ``allow_fill=True`` will place `fill_value` in those positions.
>>> pd.api.extensions.take(np.array([10, 20, 30]), [0, 0, -1], allow_fill=True) array([10., 10., nan])
>>> pd.api.extensions.take(np.array([10, 20, 30]), [0, 0, -1], allow_fill=True, ... fill_value=-10) array([ 10, 10, -10]) """ if not isinstance(arr, (np.ndarray, ABCExtensionArray, ABCIndex, ABCSeries)): # GH#52981 warnings.warn( "pd.api.extensions.take accepting non-standard inputs is deprecated " "and will raise in a future version. Pass either a numpy.ndarray, " "ExtensionArray, Index, or Series instead.", FutureWarning, stacklevel=find_stack_level(), )
if not is_array_like(arr): arr = np.asarray(arr)
indices = ensure_platform_int(indices)
if allow_fill: # Pandas style, -1 means NA validate_indices(indices, arr.shape[axis]) result = take_nd( arr, indices, axis=axis, allow_fill=True, fill_value=fill_value ) else: # NumPy style result = arr.take(indices, axis=axis) return result
# ------------ ## searchsorted ## ------------ #
def searchsorted( arr: ArrayLike, value: NumpyValueArrayLike | ExtensionArray, side: Literal["left", "right"] = "left", sorter: NumpySorter | None = None,) -> npt.NDArray[np.intp] | np.intp: """ Find indices where elements should be inserted to maintain order.
Find the indices into a sorted array `arr` (a) such that, if the corresponding elements in `value` were inserted before the indices, the order of `arr` would be preserved.
Assuming that `arr` is sorted:
====== ================================ `side` returned index `i` satisfies ====== ================================ left ``arr[i-1] < value <= self[i]`` right ``arr[i-1] <= value < self[i]`` ====== ================================
Parameters ---------- arr: np.ndarray, ExtensionArray, Series Input array. If `sorter` is None, then it must be sorted in ascending order, otherwise `sorter` must be an array of indices that sort it. value : array-like or scalar Values to insert into `arr`. side : {'left', 'right'}, optional If 'left', the index of the first suitable location found is given. If 'right', return the last such index. If there is no suitable index, return either 0 or N (where N is the length of `self`). sorter : 1-D array-like, optional Optional array of integer indices that sort array a into ascending order. They are typically the result of argsort.
Returns ------- array of ints or int If value is array-like, array of insertion points. If value is scalar, a single integer.
See Also -------- numpy.searchsorted : Similar method from NumPy. """ if sorter is not None: sorter = ensure_platform_int(sorter)
if ( isinstance(arr, np.ndarray) and arr.dtype.kind in "iu" and (is_integer(value) or is_integer_dtype(value)) ): # if `arr` and `value` have different dtypes, `arr` would be # recast by numpy, causing a slow search. # Before searching below, we therefore try to give `value` the # same dtype as `arr`, while guarding against integer overflows. iinfo = np.iinfo(arr.dtype.type) value_arr = np.array([value]) if is_integer(value) else np.array(value) if (value_arr >= iinfo.min).all() and (value_arr <= iinfo.max).all(): # value within bounds, so no overflow, so can convert value dtype # to dtype of arr dtype = arr.dtype else: dtype = value_arr.dtype
if is_integer(value): # We know that value is int value = cast(int, dtype.type(value)) else: value = pd_array(cast(ArrayLike, value), dtype=dtype) else: # E.g. if `arr` is an array with dtype='datetime64[ns]' # and `value` is a pd.Timestamp, we may need to convert value arr = ensure_wrapped_if_datetimelike(arr)
# Argument 1 to "searchsorted" of "ndarray" has incompatible type # "Union[NumpyValueArrayLike, ExtensionArray]"; expected "NumpyValueArrayLike" return arr.searchsorted(value, side=side, sorter=sorter) # type: ignore[arg-type]
# ---- ## diff ## ---- #
_diff_special = {"float64", "float32", "int64", "int32", "int16", "int8"}
def diff(arr, n: int, axis: AxisInt = 0): """ difference of n between self, analogous to s-s.shift(n)
Parameters ---------- arr : ndarray or ExtensionArray n : int number of periods axis : {0, 1} axis to shift on stacklevel : int, default 3 The stacklevel for the lost dtype warning.
Returns ------- shifted """
n = int(n) na = np.nan dtype = arr.dtype
is_bool = is_bool_dtype(dtype) if is_bool: op = operator.xor else: op = operator.sub
if isinstance(dtype, NumpyEADtype): # NumpyExtensionArray cannot necessarily hold shifted versions of itself. arr = arr.to_numpy() dtype = arr.dtype
if not isinstance(arr, np.ndarray): # i.e ExtensionArray if hasattr(arr, f"__{op.__name__}__"): if axis != 0: raise ValueError(f"cannot diff {type(arr).__name__} on axis={axis}") return op(arr, arr.shift(n)) else: raise TypeError( f"{type(arr).__name__} has no 'diff' method. " "Convert to a suitable dtype prior to calling 'diff'." )
is_timedelta = False if arr.dtype.kind in "mM": dtype = np.int64 arr = arr.view("i8") na = iNaT is_timedelta = True
elif is_bool: # We have to cast in order to be able to hold np.nan dtype = np.object_
elif dtype.kind in "iu": # We have to cast in order to be able to hold np.nan
# int8, int16 are incompatible with float64, # see https://github.com/cython/cython/issues/2646 if arr.dtype.name in ["int8", "int16"]: dtype = np.float32 else: dtype = np.float64
orig_ndim = arr.ndim if orig_ndim == 1: # reshape so we can always use algos.diff_2d arr = arr.reshape(-1, 1) # TODO: require axis == 0
dtype = np.dtype(dtype) out_arr = np.empty(arr.shape, dtype=dtype)
na_indexer = [slice(None)] * 2 na_indexer[axis] = slice(None, n) if n >= 0 else slice(n, None) out_arr[tuple(na_indexer)] = na
if arr.dtype.name in _diff_special: # TODO: can diff_2d dtype specialization troubles be fixed by defining # out_arr inside diff_2d? algos.diff_2d(arr, out_arr, n, axis, datetimelike=is_timedelta) else: # To keep mypy happy, _res_indexer is a list while res_indexer is # a tuple, ditto for lag_indexer. _res_indexer = [slice(None)] * 2 _res_indexer[axis] = slice(n, None) if n >= 0 else slice(None, n) res_indexer = tuple(_res_indexer)
_lag_indexer = [slice(None)] * 2 _lag_indexer[axis] = slice(None, -n) if n > 0 else slice(-n, None) lag_indexer = tuple(_lag_indexer)
out_arr[res_indexer] = op(arr[res_indexer], arr[lag_indexer])
if is_timedelta: out_arr = out_arr.view("timedelta64[ns]")
if orig_ndim == 1: out_arr = out_arr[:, 0] return out_arr
# --------------------------------------------------------------------# Helper functions
# Note: safe_sort is in algorithms.py instead of sorting.py because it is# low-dependency, is used in this module, and used private methods from# this module.def safe_sort( values: Index | ArrayLike, codes: npt.NDArray[np.intp] | None = None, use_na_sentinel: bool = True, assume_unique: bool = False, verify: bool = True,) -> AnyArrayLike | tuple[AnyArrayLike, np.ndarray]: """ Sort ``values`` and reorder corresponding ``codes``.
``values`` should be unique if ``codes`` is not None. Safe for use with mixed types (int, str), orders ints before strs.
Parameters ---------- values : list-like Sequence; must be unique if ``codes`` is not None. codes : np.ndarray[intp] or None, default None Indices to ``values``. All out of bound indices are treated as "not found" and will be masked with ``-1``. use_na_sentinel : bool, default True If True, the sentinel -1 will be used for NaN values. If False, NaN values will be encoded as non-negative integers and will not drop the NaN from the uniques of the values. assume_unique : bool, default False When True, ``values`` are assumed to be unique, which can speed up the calculation. Ignored when ``codes`` is None. verify : bool, default True Check if codes are out of bound for the values and put out of bound codes equal to ``-1``. If ``verify=False``, it is assumed there are no out of bound codes. Ignored when ``codes`` is None.
Returns ------- ordered : AnyArrayLike Sorted ``values`` new_codes : ndarray Reordered ``codes``; returned when ``codes`` is not None.
Raises ------ TypeError * If ``values`` is not list-like or if ``codes`` is neither None nor list-like * If ``values`` cannot be sorted ValueError * If ``codes`` is not None and ``values`` contain duplicates. """ if not isinstance(values, (np.ndarray, ABCExtensionArray, ABCIndex)): raise TypeError( "Only np.ndarray, ExtensionArray, and Index objects are allowed to " "be passed to safe_sort as values" )
sorter = None ordered: AnyArrayLike
if ( not isinstance(values.dtype, ExtensionDtype) and lib.infer_dtype(values, skipna=False) == "mixed-integer" ): ordered = _sort_mixed(values) else: try: sorter = values.argsort() ordered = values.take(sorter) except (TypeError, decimal.InvalidOperation): # Previous sorters failed or were not applicable, try `_sort_mixed` # which would work, but which fails for special case of 1d arrays # with tuples. if values.size and isinstance(values[0], tuple): # error: Argument 1 to "_sort_tuples" has incompatible type # "Union[Index, ExtensionArray, ndarray[Any, Any]]"; expected # "ndarray[Any, Any]" ordered = _sort_tuples(values) # type: ignore[arg-type] else: ordered = _sort_mixed(values)
# codes:
if codes is None: return ordered
if not is_list_like(codes): raise TypeError( "Only list-like objects or None are allowed to " "be passed to safe_sort as codes" ) codes = ensure_platform_int(np.asarray(codes))
if not assume_unique and not len(unique(values)) == len(values): raise ValueError("values should be unique if codes is not None")
if sorter is None: # mixed types # error: Argument 1 to "_get_hashtable_algo" has incompatible type # "Union[Index, ExtensionArray, ndarray[Any, Any]]"; expected # "ndarray[Any, Any]" hash_klass, values = _get_hashtable_algo(values) # type: ignore[arg-type] t = hash_klass(len(values)) t.map_locations(values) sorter = ensure_platform_int(t.lookup(ordered))
if use_na_sentinel: # take_nd is faster, but only works for na_sentinels of -1 order2 = sorter.argsort() if verify: mask = (codes < -len(values)) | (codes >= len(values)) codes[mask] = 0 else: mask = None new_codes = take_nd(order2, codes, fill_value=-1) else: reverse_indexer = np.empty(len(sorter), dtype=int) reverse_indexer.put(sorter, np.arange(len(sorter))) # Out of bound indices will be masked with `-1` next, so we # may deal with them here without performance loss using `mode='wrap'` new_codes = reverse_indexer.take(codes, mode="wrap")
if use_na_sentinel: mask = codes == -1 if verify: mask = mask | (codes < -len(values)) | (codes >= len(values))
if use_na_sentinel and mask is not None: np.putmask(new_codes, mask, -1)
return ordered, ensure_platform_int(new_codes)
def _sort_mixed(values) -> AnyArrayLike: """order ints before strings before nulls in 1d arrays""" str_pos = np.array([isinstance(x, str) for x in values], dtype=bool) null_pos = np.array([isna(x) for x in values], dtype=bool) num_pos = ~str_pos & ~null_pos str_argsort = np.argsort(values[str_pos]) num_argsort = np.argsort(values[num_pos]) # convert boolean arrays to positional indices, then order by underlying values str_locs = str_pos.nonzero()[0].take(str_argsort) num_locs = num_pos.nonzero()[0].take(num_argsort) null_locs = null_pos.nonzero()[0] locs = np.concatenate([num_locs, str_locs, null_locs]) return values.take(locs)
def _sort_tuples(values: np.ndarray) -> np.ndarray: """ Convert array of tuples (1d) to array of arrays (2d). We need to keep the columns separately as they contain different types and nans (can't use `np.sort` as it may fail when str and nan are mixed in a column as types cannot be compared). """ from pandas.core.internals.construction import to_arrays from pandas.core.sorting import lexsort_indexer
arrays, _ = to_arrays(values, None) indexer = lexsort_indexer(arrays, orders=True) return values[indexer]
def union_with_duplicates( lvals: ArrayLike | Index, rvals: ArrayLike | Index) -> ArrayLike | Index: """ Extracts the union from lvals and rvals with respect to duplicates and nans in both arrays.
Parameters ---------- lvals: np.ndarray or ExtensionArray left values which is ordered in front. rvals: np.ndarray or ExtensionArray right values ordered after lvals.
Returns ------- np.ndarray or ExtensionArray Containing the unsorted union of both arrays.
Notes ----- Caller is responsible for ensuring lvals.dtype == rvals.dtype. """ from pandas import Series
with warnings.catch_warnings(): # filter warning from object dtype inference; we will end up discarding # the index here, so the deprecation does not affect the end result here. warnings.filterwarnings( "ignore", "The behavior of value_counts with object-dtype is deprecated", category=FutureWarning, ) l_count = value_counts_internal(lvals, dropna=False) r_count = value_counts_internal(rvals, dropna=False) l_count, r_count = l_count.align(r_count, fill_value=0) final_count = np.maximum(l_count.values, r_count.values) final_count = Series(final_count, index=l_count.index, dtype="int", copy=False) if isinstance(lvals, ABCMultiIndex) and isinstance(rvals, ABCMultiIndex): unique_vals = lvals.append(rvals).unique() else: if isinstance(lvals, ABCIndex): lvals = lvals._values if isinstance(rvals, ABCIndex): rvals = rvals._values # error: List item 0 has incompatible type "Union[ExtensionArray, # ndarray[Any, Any], Index]"; expected "Union[ExtensionArray, # ndarray[Any, Any]]" combined = concat_compat([lvals, rvals]) # type: ignore[list-item] unique_vals = unique(combined) unique_vals = ensure_wrapped_if_datetimelike(unique_vals) repeats = final_count.reindex(unique_vals).values return np.repeat(unique_vals, repeats)
def map_array( arr: ArrayLike, mapper, na_action: Literal["ignore"] | None = None, convert: bool = True,) -> np.ndarray | ExtensionArray | Index: """ Map values using an input mapping or function.
Parameters ---------- mapper : function, dict, or Series Mapping correspondence. na_action : {None, 'ignore'}, default None If 'ignore', propagate NA values, without passing them to the mapping correspondence. convert : bool, default True Try to find better dtype for elementwise function results. If False, leave as dtype=object.
Returns ------- Union[ndarray, Index, ExtensionArray] The output of the mapping function applied to the array. If the function returns a tuple with more than one element a MultiIndex will be returned. """ if na_action not in (None, "ignore"): msg = f"na_action must either be 'ignore' or None, {na_action} was passed" raise ValueError(msg)
# we can fastpath dict/Series to an efficient map # as we know that we are not going to have to yield # python types if is_dict_like(mapper): if isinstance(mapper, dict) and hasattr(mapper, "__missing__"): # If a dictionary subclass defines a default value method, # convert mapper to a lookup function (GH #15999). dict_with_default = mapper mapper = lambda x: dict_with_default[ np.nan if isinstance(x, float) and np.isnan(x) else x ] else: # Dictionary does not have a default. Thus it's safe to # convert to an Series for efficiency. # we specify the keys here to handle the # possibility that they are tuples
# The return value of mapping with an empty mapper is # expected to be pd.Series(np.nan, ...). As np.nan is # of dtype float64 the return value of this method should # be float64 as well from pandas import Series
if len(mapper) == 0: mapper = Series(mapper, dtype=np.float64) else: mapper = Series(mapper)
if isinstance(mapper, ABCSeries): if na_action == "ignore": mapper = mapper[mapper.index.notna()]
# Since values were input this means we came from either # a dict or a series and mapper should be an index indexer = mapper.index.get_indexer(arr) new_values = take_nd(mapper._values, indexer)
return new_values
if not len(arr): return arr.copy()
# we must convert to python types values = arr.astype(object, copy=False) if na_action is None: return lib.map_infer(values, mapper, convert=convert) else: return lib.map_infer_mask( values, mapper, mask=isna(values).view(np.uint8), convert=convert )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140from pandas._libs import ( NaT, Period, Timedelta, Timestamp,)from pandas._libs.missing import NA
from pandas.core.dtypes.dtypes import ( ArrowDtype, CategoricalDtype, DatetimeTZDtype, IntervalDtype, PeriodDtype,)from pandas.core.dtypes.missing import ( isna, isnull, notna, notnull,)
from pandas.core.algorithms import ( factorize, unique, value_counts,)from pandas.core.arrays import Categoricalfrom pandas.core.arrays.boolean import BooleanDtypefrom pandas.core.arrays.floating import ( Float32Dtype, Float64Dtype,)from pandas.core.arrays.integer import ( Int8Dtype, Int16Dtype, Int32Dtype, Int64Dtype, UInt8Dtype, UInt16Dtype, UInt32Dtype, UInt64Dtype,)from pandas.core.arrays.string_ import StringDtypefrom pandas.core.construction import arrayfrom pandas.core.flags import Flagsfrom pandas.core.groupby import ( Grouper, NamedAgg,)from pandas.core.indexes.api import ( CategoricalIndex, DatetimeIndex, Index, IntervalIndex, MultiIndex, PeriodIndex, RangeIndex, TimedeltaIndex,)from pandas.core.indexes.datetimes import ( bdate_range, date_range,)from pandas.core.indexes.interval import ( Interval, interval_range,)from pandas.core.indexes.period import period_rangefrom pandas.core.indexes.timedeltas import timedelta_rangefrom pandas.core.indexing import IndexSlicefrom pandas.core.series import Seriesfrom pandas.core.tools.datetimes import to_datetimefrom pandas.core.tools.numeric import to_numericfrom pandas.core.tools.timedeltas import to_timedelta
from pandas.io.formats.format import set_eng_float_formatfrom pandas.tseries.offsets import DateOffset
# DataFrame needs to be imported after NamedAgg to avoid a circular importfrom pandas.core.frame import DataFrame # isort:skip
__all__ = [ "array", "ArrowDtype", "bdate_range", "BooleanDtype", "Categorical", "CategoricalDtype", "CategoricalIndex", "DataFrame", "DateOffset", "date_range", "DatetimeIndex", "DatetimeTZDtype", "factorize", "Flags", "Float32Dtype", "Float64Dtype", "Grouper", "Index", "IndexSlice", "Int16Dtype", "Int32Dtype", "Int64Dtype", "Int8Dtype", "Interval", "IntervalDtype", "IntervalIndex", "interval_range", "isna", "isnull", "MultiIndex", "NA", "NamedAgg", "NaT", "notna", "notnull", "Period", "PeriodDtype", "PeriodIndex", "period_range", "RangeIndex", "Series", "set_eng_float_format", "StringDtype", "Timedelta", "TimedeltaIndex", "timedelta_range", "Timestamp", "to_datetime", "to_numeric", "to_timedelta", "UInt16Dtype", "UInt32Dtype", "UInt64Dtype", "UInt8Dtype", "unique", "value_counts",]1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062from __future__ import annotations
import abcfrom collections import defaultdictimport functoolsfrom functools import partialimport inspectfrom typing import ( TYPE_CHECKING, Any, Callable, Literal, cast,)import warnings
import numpy as np
from pandas._config import option_context
from pandas._libs import libfrom pandas._libs.internals import BlockValuesRefsfrom pandas._typing import ( AggFuncType, AggFuncTypeBase, AggFuncTypeDict, AggObjType, Axis, AxisInt, NDFrameT, npt,)from pandas.compat._optional import import_optional_dependencyfrom pandas.errors import SpecificationErrorfrom pandas.util._decorators import cache_readonlyfrom pandas.util._exceptions import find_stack_level
from pandas.core.dtypes.cast import is_nested_objectfrom pandas.core.dtypes.common import ( is_dict_like, is_extension_array_dtype, is_list_like, is_numeric_dtype, is_sequence,)from pandas.core.dtypes.dtypes import ( CategoricalDtype, ExtensionDtype,)from pandas.core.dtypes.generic import ( ABCDataFrame, ABCNDFrame, ABCSeries,)
from pandas.core._numba.executor import generate_apply_looperimport pandas.core.common as comfrom pandas.core.construction import ensure_wrapped_if_datetimelike
if TYPE_CHECKING: from collections.abc import ( Generator, Hashable, Iterable, MutableMapping, Sequence, )
from pandas import ( DataFrame, Index, Series, ) from pandas.core.groupby import GroupBy from pandas.core.resample import Resampler from pandas.core.window.rolling import BaseWindow
ResType = dict[int, Any]
def frame_apply( obj: DataFrame, func: AggFuncType, axis: Axis = 0, raw: bool = False, result_type: str | None = None, by_row: Literal[False, "compat"] = "compat", engine: str = "python", engine_kwargs: dict[str, bool] | None = None, args=None, kwargs=None,) -> FrameApply: """construct and return a row or column based frame apply object""" axis = obj._get_axis_number(axis) klass: type[FrameApply] if axis == 0: klass = FrameRowApply elif axis == 1: klass = FrameColumnApply
_, func, _, _ = reconstruct_func(func, **kwargs) assert func is not None
return klass( obj, func, raw=raw, result_type=result_type, by_row=by_row, engine=engine, engine_kwargs=engine_kwargs, args=args, kwargs=kwargs, )
class Apply(metaclass=abc.ABCMeta): axis: AxisInt
def __init__( self, obj: AggObjType, func: AggFuncType, raw: bool, result_type: str | None, *, by_row: Literal[False, "compat", "_compat"] = "compat", engine: str = "python", engine_kwargs: dict[str, bool] | None = None, args, kwargs, ) -> None: self.obj = obj self.raw = raw
assert by_row is False or by_row in ["compat", "_compat"] self.by_row = by_row
self.args = args or () self.kwargs = kwargs or {}
self.engine = engine self.engine_kwargs = {} if engine_kwargs is None else engine_kwargs
if result_type not in [None, "reduce", "broadcast", "expand"]: raise ValueError( "invalid value for result_type, must be one " "of {None, 'reduce', 'broadcast', 'expand'}" )
self.result_type = result_type
self.func = func
@abc.abstractmethod def apply(self) -> DataFrame | Series: pass
@abc.abstractmethod def agg_or_apply_list_like( self, op_name: Literal["agg", "apply"] ) -> DataFrame | Series: pass
@abc.abstractmethod def agg_or_apply_dict_like( self, op_name: Literal["agg", "apply"] ) -> DataFrame | Series: pass
def agg(self) -> DataFrame | Series | None: """ Provide an implementation for the aggregators.
Returns ------- Result of aggregation, or None if agg cannot be performed by this method. """ obj = self.obj func = self.func args = self.args kwargs = self.kwargs
if isinstance(func, str): return self.apply_str()
if is_dict_like(func): return self.agg_dict_like() elif is_list_like(func): # we require a list, but not a 'str' return self.agg_list_like()
if callable(func): f = com.get_cython_func(func) if f and not args and not kwargs: warn_alias_replacement(obj, func, f) return getattr(obj, f)()
# caller can react return None
def transform(self) -> DataFrame | Series: """ Transform a DataFrame or Series.
Returns ------- DataFrame or Series Result of applying ``func`` along the given axis of the Series or DataFrame.
Raises ------ ValueError If the transform function fails or does not transform. """ obj = self.obj func = self.func axis = self.axis args = self.args kwargs = self.kwargs
is_series = obj.ndim == 1
if obj._get_axis_number(axis) == 1: assert not is_series return obj.T.transform(func, 0, *args, **kwargs).T
if is_list_like(func) and not is_dict_like(func): func = cast(list[AggFuncTypeBase], func) # Convert func equivalent dict if is_series: func = {com.get_callable_name(v) or v: v for v in func} else: func = {col: func for col in obj}
if is_dict_like(func): func = cast(AggFuncTypeDict, func) return self.transform_dict_like(func)
# func is either str or callable func = cast(AggFuncTypeBase, func) try: result = self.transform_str_or_callable(func) except TypeError: raise except Exception as err: raise ValueError("Transform function failed") from err
# Functions that transform may return empty Series/DataFrame # when the dtype is not appropriate if ( isinstance(result, (ABCSeries, ABCDataFrame)) and result.empty and not obj.empty ): raise ValueError("Transform function failed") # error: Argument 1 to "__get__" of "AxisProperty" has incompatible type # "Union[Series, DataFrame, GroupBy[Any], SeriesGroupBy, # DataFrameGroupBy, BaseWindow, Resampler]"; expected "Union[DataFrame, # Series]" if not isinstance(result, (ABCSeries, ABCDataFrame)) or not result.index.equals( obj.index # type: ignore[arg-type] ): raise ValueError("Function did not transform")
return result
def transform_dict_like(self, func) -> DataFrame: """ Compute transform in the case of a dict-like func """ from pandas.core.reshape.concat import concat
obj = self.obj args = self.args kwargs = self.kwargs
# transform is currently only for Series/DataFrame assert isinstance(obj, ABCNDFrame)
if len(func) == 0: raise ValueError("No transform functions were provided")
func = self.normalize_dictlike_arg("transform", obj, func)
results: dict[Hashable, DataFrame | Series] = {} for name, how in func.items(): colg = obj._gotitem(name, ndim=1) results[name] = colg.transform(how, 0, *args, **kwargs) return concat(results, axis=1)
def transform_str_or_callable(self, func) -> DataFrame | Series: """ Compute transform in the case of a string or callable func """ obj = self.obj args = self.args kwargs = self.kwargs
if isinstance(func, str): return self._apply_str(obj, func, *args, **kwargs)
if not args and not kwargs: f = com.get_cython_func(func) if f: warn_alias_replacement(obj, func, f) return getattr(obj, f)()
# Two possible ways to use a UDF - apply or call directly try: return obj.apply(func, args=args, **kwargs) except Exception: return func(obj, *args, **kwargs)
def agg_list_like(self) -> DataFrame | Series: """ Compute aggregation in the case of a list-like argument.
Returns ------- Result of aggregation. """ return self.agg_or_apply_list_like(op_name="agg")
def compute_list_like( self, op_name: Literal["agg", "apply"], selected_obj: Series | DataFrame, kwargs: dict[str, Any], ) -> tuple[list[Hashable] | Index, list[Any]]: """ Compute agg/apply results for like-like input.
Parameters ---------- op_name : {"agg", "apply"} Operation being performed. selected_obj : Series or DataFrame Data to perform operation on. kwargs : dict Keyword arguments to pass to the functions.
Returns ------- keys : list[Hashable] or Index Index labels for result. results : list Data for result. When aggregating with a Series, this can contain any Python objects. """ func = cast(list[AggFuncTypeBase], self.func) obj = self.obj
results = [] keys = []
# degenerate case if selected_obj.ndim == 1: for a in func: colg = obj._gotitem(selected_obj.name, ndim=1, subset=selected_obj) args = ( [self.axis, *self.args] if include_axis(op_name, colg) else self.args ) new_res = getattr(colg, op_name)(a, *args, **kwargs) results.append(new_res)
# make sure we find a good name name = com.get_callable_name(a) or a keys.append(name)
else: indices = [] for index, col in enumerate(selected_obj): colg = obj._gotitem(col, ndim=1, subset=selected_obj.iloc[:, index]) args = ( [self.axis, *self.args] if include_axis(op_name, colg) else self.args ) new_res = getattr(colg, op_name)(func, *args, **kwargs) results.append(new_res) indices.append(index) # error: Incompatible types in assignment (expression has type "Any | # Index", variable has type "list[Any | Callable[..., Any] | str]") keys = selected_obj.columns.take(indices) # type: ignore[assignment]
return keys, results
def wrap_results_list_like( self, keys: Iterable[Hashable], results: list[Series | DataFrame] ): from pandas.core.reshape.concat import concat
obj = self.obj
try: return concat(results, keys=keys, axis=1, sort=False) except TypeError as err: # we are concatting non-NDFrame objects, # e.g. a list of scalars from pandas import Series
result = Series(results, index=keys, name=obj.name) if is_nested_object(result): raise ValueError( "cannot combine transform and aggregation operations" ) from err return result
def agg_dict_like(self) -> DataFrame | Series: """ Compute aggregation in the case of a dict-like argument.
Returns ------- Result of aggregation. """ return self.agg_or_apply_dict_like(op_name="agg")
def compute_dict_like( self, op_name: Literal["agg", "apply"], selected_obj: Series | DataFrame, selection: Hashable | Sequence[Hashable], kwargs: dict[str, Any], ) -> tuple[list[Hashable], list[Any]]: """ Compute agg/apply results for dict-like input.
Parameters ---------- op_name : {"agg", "apply"} Operation being performed. selected_obj : Series or DataFrame Data to perform operation on. selection : hashable or sequence of hashables Used by GroupBy, Window, and Resample if selection is applied to the object. kwargs : dict Keyword arguments to pass to the functions.
Returns ------- keys : list[hashable] Index labels for result. results : list Data for result. When aggregating with a Series, this can contain any Python object. """ from pandas.core.groupby.generic import ( DataFrameGroupBy, SeriesGroupBy, )
obj = self.obj is_groupby = isinstance(obj, (DataFrameGroupBy, SeriesGroupBy)) func = cast(AggFuncTypeDict, self.func) func = self.normalize_dictlike_arg(op_name, selected_obj, func)
is_non_unique_col = ( selected_obj.ndim == 2 and selected_obj.columns.nunique() < len(selected_obj.columns) )
if selected_obj.ndim == 1: # key only used for output colg = obj._gotitem(selection, ndim=1) results = [getattr(colg, op_name)(how, **kwargs) for _, how in func.items()] keys = list(func.keys()) elif not is_groupby and is_non_unique_col: # key used for column selection and output # GH#51099 results = [] keys = [] for key, how in func.items(): indices = selected_obj.columns.get_indexer_for([key]) labels = selected_obj.columns.take(indices) label_to_indices = defaultdict(list) for index, label in zip(indices, labels): label_to_indices[label].append(index)
key_data = [ getattr(selected_obj._ixs(indice, axis=1), op_name)(how, **kwargs) for label, indices in label_to_indices.items() for indice in indices ]
keys += [key] * len(key_data) results += key_data else: # key used for column selection and output results = [ getattr(obj._gotitem(key, ndim=1), op_name)(how, **kwargs) for key, how in func.items() ] keys = list(func.keys())
return keys, results
def wrap_results_dict_like( self, selected_obj: Series | DataFrame, result_index: list[Hashable], result_data: list, ): from pandas import Index from pandas.core.reshape.concat import concat
obj = self.obj
# Avoid making two isinstance calls in all and any below is_ndframe = [isinstance(r, ABCNDFrame) for r in result_data]
if all(is_ndframe): results = dict(zip(result_index, result_data)) keys_to_use: Iterable[Hashable] keys_to_use = [k for k in result_index if not results[k].empty] # Have to check, if at least one DataFrame is not empty. keys_to_use = keys_to_use if keys_to_use != [] else result_index if selected_obj.ndim == 2: # keys are columns, so we can preserve names ktu = Index(keys_to_use) ktu._set_names(selected_obj.columns.names) keys_to_use = ktu
axis: AxisInt = 0 if isinstance(obj, ABCSeries) else 1 result = concat( {k: results[k] for k in keys_to_use}, axis=axis, keys=keys_to_use, ) elif any(is_ndframe): # There is a mix of NDFrames and scalars raise ValueError( "cannot perform both aggregation " "and transformation operations " "simultaneously" ) else: from pandas import Series
# we have a list of scalars # GH 36212 use name only if obj is a series if obj.ndim == 1: obj = cast("Series", obj) name = obj.name else: name = None
result = Series(result_data, index=result_index, name=name)
return result
def apply_str(self) -> DataFrame | Series: """ Compute apply in case of a string.
Returns ------- result: Series or DataFrame """ # Caller is responsible for checking isinstance(self.f, str) func = cast(str, self.func)
obj = self.obj
from pandas.core.groupby.generic import ( DataFrameGroupBy, SeriesGroupBy, )
# Support for `frame.transform('method')` # Some methods (shift, etc.) require the axis argument, others # don't, so inspect and insert if necessary. method = getattr(obj, func, None) if callable(method): sig = inspect.getfullargspec(method) arg_names = (*sig.args, *sig.kwonlyargs) if self.axis != 0 and ( "axis" not in arg_names or func in ("corrwith", "skew") ): raise ValueError(f"Operation {func} does not support axis=1") if "axis" in arg_names: if isinstance(obj, (SeriesGroupBy, DataFrameGroupBy)): # Try to avoid FutureWarning for deprecated axis keyword; # If self.axis matches the axis we would get by not passing # axis, we safely exclude the keyword.
default_axis = 0 if func in ["idxmax", "idxmin"]: # DataFrameGroupBy.idxmax, idxmin axis defaults to self.axis, # whereas other axis keywords default to 0 default_axis = self.obj.axis
if default_axis != self.axis: self.kwargs["axis"] = self.axis else: self.kwargs["axis"] = self.axis return self._apply_str(obj, func, *self.args, **self.kwargs)
def apply_list_or_dict_like(self) -> DataFrame | Series: """ Compute apply in case of a list-like or dict-like.
Returns ------- result: Series, DataFrame, or None Result when self.func is a list-like or dict-like, None otherwise. """
if self.engine == "numba": raise NotImplementedError( "The 'numba' engine doesn't support list-like/" "dict likes of callables yet." )
if self.axis == 1 and isinstance(self.obj, ABCDataFrame): return self.obj.T.apply(self.func, 0, args=self.args, **self.kwargs).T
func = self.func kwargs = self.kwargs
if is_dict_like(func): result = self.agg_or_apply_dict_like(op_name="apply") else: result = self.agg_or_apply_list_like(op_name="apply")
result = reconstruct_and_relabel_result(result, func, **kwargs)
return result
def normalize_dictlike_arg( self, how: str, obj: DataFrame | Series, func: AggFuncTypeDict ) -> AggFuncTypeDict: """ Handler for dict-like argument.
Ensures that necessary columns exist if obj is a DataFrame, and that a nested renamer is not passed. Also normalizes to all lists when values consists of a mix of list and non-lists. """ assert how in ("apply", "agg", "transform")
# Can't use func.values(); wouldn't work for a Series if ( how == "agg" and isinstance(obj, ABCSeries) and any(is_list_like(v) for _, v in func.items()) ) or (any(is_dict_like(v) for _, v in func.items())): # GH 15931 - deprecation of renaming keys raise SpecificationError("nested renamer is not supported")
if obj.ndim != 1: # Check for missing columns on a frame from pandas import Index
cols = Index(list(func.keys())).difference(obj.columns, sort=True) if len(cols) > 0: raise KeyError(f"Column(s) {list(cols)} do not exist")
aggregator_types = (list, tuple, dict)
# if we have a dict of any non-scalars # eg. {'A' : ['mean']}, normalize all to # be list-likes # Cannot use func.values() because arg may be a Series if any(isinstance(x, aggregator_types) for _, x in func.items()): new_func: AggFuncTypeDict = {} for k, v in func.items(): if not isinstance(v, aggregator_types): new_func[k] = [v] else: new_func[k] = v func = new_func return func
def _apply_str(self, obj, func: str, *args, **kwargs): """ if arg is a string, then try to operate on it: - try to find a function (or attribute) on obj - try to find a numpy function - raise """ assert isinstance(func, str)
if hasattr(obj, func): f = getattr(obj, func) if callable(f): return f(*args, **kwargs)
# people may aggregate on a non-callable attribute # but don't let them think they can pass args to it assert len(args) == 0 assert len([kwarg for kwarg in kwargs if kwarg not in ["axis"]]) == 0 return f elif hasattr(np, func) and hasattr(obj, "__array__"): # in particular exclude Window f = getattr(np, func) return f(obj, *args, **kwargs) else: msg = f"'{func}' is not a valid function for '{type(obj).__name__}' object" raise AttributeError(msg)
class NDFrameApply(Apply): """ Methods shared by FrameApply and SeriesApply but not GroupByApply or ResamplerWindowApply """
obj: DataFrame | Series
@property def index(self) -> Index: return self.obj.index
@property def agg_axis(self) -> Index: return self.obj._get_agg_axis(self.axis)
def agg_or_apply_list_like( self, op_name: Literal["agg", "apply"] ) -> DataFrame | Series: obj = self.obj kwargs = self.kwargs
if op_name == "apply": if isinstance(self, FrameApply): by_row = self.by_row
elif isinstance(self, SeriesApply): by_row = "_compat" if self.by_row else False else: by_row = False kwargs = {**kwargs, "by_row": by_row}
if getattr(obj, "axis", 0) == 1: raise NotImplementedError("axis other than 0 is not supported")
keys, results = self.compute_list_like(op_name, obj, kwargs) result = self.wrap_results_list_like(keys, results) return result
def agg_or_apply_dict_like( self, op_name: Literal["agg", "apply"] ) -> DataFrame | Series: assert op_name in ["agg", "apply"] obj = self.obj
kwargs = {} if op_name == "apply": by_row = "_compat" if self.by_row else False kwargs.update({"by_row": by_row})
if getattr(obj, "axis", 0) == 1: raise NotImplementedError("axis other than 0 is not supported")
selection = None result_index, result_data = self.compute_dict_like( op_name, obj, selection, kwargs ) result = self.wrap_results_dict_like(obj, result_index, result_data) return result
class FrameApply(NDFrameApply): obj: DataFrame
def __init__( self, obj: AggObjType, func: AggFuncType, raw: bool, result_type: str | None, *, by_row: Literal[False, "compat"] = False, engine: str = "python", engine_kwargs: dict[str, bool] | None = None, args, kwargs, ) -> None: if by_row is not False and by_row != "compat": raise ValueError(f"by_row={by_row} not allowed") super().__init__( obj, func, raw, result_type, by_row=by_row, engine=engine, engine_kwargs=engine_kwargs, args=args, kwargs=kwargs, )
# --------------------------------------------------------------- # Abstract Methods
@property @abc.abstractmethod def result_index(self) -> Index: pass
@property @abc.abstractmethod def result_columns(self) -> Index: pass
@property @abc.abstractmethod def series_generator(self) -> Generator[Series, None, None]: pass
@staticmethod @functools.cache @abc.abstractmethod def generate_numba_apply_func( func, nogil=True, nopython=True, parallel=False ) -> Callable[[npt.NDArray, Index, Index], dict[int, Any]]: pass
@abc.abstractmethod def apply_with_numba(self): pass
def validate_values_for_numba(self): # Validate column dtyps all OK for colname, dtype in self.obj.dtypes.items(): if not is_numeric_dtype(dtype): raise ValueError( f"Column {colname} must have a numeric dtype. " f"Found '{dtype}' instead" ) if is_extension_array_dtype(dtype): raise ValueError( f"Column {colname} is backed by an extension array, " f"which is not supported by the numba engine." )
@abc.abstractmethod def wrap_results_for_axis( self, results: ResType, res_index: Index ) -> DataFrame | Series: pass
# ---------------------------------------------------------------
@property def res_columns(self) -> Index: return self.result_columns
@property def columns(self) -> Index: return self.obj.columns
@cache_readonly def values(self): return self.obj.values
def apply(self) -> DataFrame | Series: """compute the results"""
# dispatch to handle list-like or dict-like if is_list_like(self.func): if self.engine == "numba": raise NotImplementedError( "the 'numba' engine doesn't support lists of callables yet" ) return self.apply_list_or_dict_like()
# all empty if len(self.columns) == 0 and len(self.index) == 0: return self.apply_empty_result()
# string dispatch if isinstance(self.func, str): if self.engine == "numba": raise NotImplementedError( "the 'numba' engine doesn't support using " "a string as the callable function" ) return self.apply_str()
# ufunc elif isinstance(self.func, np.ufunc): if self.engine == "numba": raise NotImplementedError( "the 'numba' engine doesn't support " "using a numpy ufunc as the callable function" ) with np.errstate(all="ignore"): results = self.obj._mgr.apply("apply", func=self.func) # _constructor will retain self.index and self.columns return self.obj._constructor_from_mgr(results, axes=results.axes)
# broadcasting if self.result_type == "broadcast": if self.engine == "numba": raise NotImplementedError( "the 'numba' engine doesn't support result_type='broadcast'" ) return self.apply_broadcast(self.obj)
# one axis empty elif not all(self.obj.shape): return self.apply_empty_result()
# raw elif self.raw: return self.apply_raw(engine=self.engine, engine_kwargs=self.engine_kwargs)
return self.apply_standard()
def agg(self): obj = self.obj axis = self.axis
# TODO: Avoid having to change state self.obj = self.obj if self.axis == 0 else self.obj.T self.axis = 0
result = None try: result = super().agg() finally: self.obj = obj self.axis = axis
if axis == 1: result = result.T if result is not None else result
if result is None: result = self.obj.apply(self.func, axis, args=self.args, **self.kwargs)
return result
def apply_empty_result(self): """ we have an empty result; at least 1 axis is 0
we will try to apply the function to an empty series in order to see if this is a reduction function """ assert callable(self.func)
# we are not asked to reduce or infer reduction # so just return a copy of the existing object if self.result_type not in ["reduce", None]: return self.obj.copy()
# we may need to infer should_reduce = self.result_type == "reduce"
from pandas import Series
if not should_reduce: try: if self.axis == 0: r = self.func( Series([], dtype=np.float64), *self.args, **self.kwargs ) else: r = self.func( Series(index=self.columns, dtype=np.float64), *self.args, **self.kwargs, ) except Exception: pass else: should_reduce = not isinstance(r, Series)
if should_reduce: if len(self.agg_axis): r = self.func(Series([], dtype=np.float64), *self.args, **self.kwargs) else: r = np.nan
return self.obj._constructor_sliced(r, index=self.agg_axis) else: return self.obj.copy()
def apply_raw(self, engine="python", engine_kwargs=None): """apply to the values as a numpy array"""
def wrap_function(func): """ Wrap user supplied function to work around numpy issue.
see https://github.com/numpy/numpy/issues/8352 """
def wrapper(*args, **kwargs): result = func(*args, **kwargs) if isinstance(result, str): result = np.array(result, dtype=object) return result
return wrapper
if engine == "numba": engine_kwargs = {} if engine_kwargs is None else engine_kwargs
# error: Argument 1 to "__call__" of "_lru_cache_wrapper" has # incompatible type "Callable[..., Any] | str | list[Callable # [..., Any] | str] | dict[Hashable,Callable[..., Any] | str | # list[Callable[..., Any] | str]]"; expected "Hashable" nb_looper = generate_apply_looper( self.func, **engine_kwargs # type: ignore[arg-type] ) result = nb_looper(self.values, self.axis) # If we made the result 2-D, squeeze it back to 1-D result = np.squeeze(result) else: result = np.apply_along_axis( wrap_function(self.func), self.axis, self.values, *self.args, **self.kwargs, )
# TODO: mixed type case if result.ndim == 2: return self.obj._constructor(result, index=self.index, columns=self.columns) else: return self.obj._constructor_sliced(result, index=self.agg_axis)
def apply_broadcast(self, target: DataFrame) -> DataFrame: assert callable(self.func)
result_values = np.empty_like(target.values)
# axis which we want to compare compliance result_compare = target.shape[0]
for i, col in enumerate(target.columns): res = self.func(target[col], *self.args, **self.kwargs) ares = np.asarray(res).ndim
# must be a scalar or 1d if ares > 1: raise ValueError("too many dims to broadcast") if ares == 1: # must match return dim if result_compare != len(res): raise ValueError("cannot broadcast result")
result_values[:, i] = res
# we *always* preserve the original index / columns result = self.obj._constructor( result_values, index=target.index, columns=target.columns ) return result
def apply_standard(self): if self.engine == "python": results, res_index = self.apply_series_generator() else: results, res_index = self.apply_series_numba()
# wrap results return self.wrap_results(results, res_index)
def apply_series_generator(self) -> tuple[ResType, Index]: assert callable(self.func)
series_gen = self.series_generator res_index = self.result_index
results = {}
with option_context("mode.chained_assignment", None): for i, v in enumerate(series_gen): # ignore SettingWithCopy here in case the user mutates results[i] = self.func(v, *self.args, **self.kwargs) if isinstance(results[i], ABCSeries): # If we have a view on v, we need to make a copy because # series_generator will swap out the underlying data results[i] = results[i].copy(deep=False)
return results, res_index
def apply_series_numba(self): if self.engine_kwargs.get("parallel", False): raise NotImplementedError( "Parallel apply is not supported when raw=False and engine='numba'" ) if not self.obj.index.is_unique or not self.columns.is_unique: raise NotImplementedError( "The index/columns must be unique when raw=False and engine='numba'" ) self.validate_values_for_numba() results = self.apply_with_numba() return results, self.result_index
def wrap_results(self, results: ResType, res_index: Index) -> DataFrame | Series: from pandas import Series
# see if we can infer the results if len(results) > 0 and 0 in results and is_sequence(results[0]): return self.wrap_results_for_axis(results, res_index)
# dict of scalars
# the default dtype of an empty Series is `object`, but this # code can be hit by df.mean() where the result should have dtype # float64 even if it's an empty Series. constructor_sliced = self.obj._constructor_sliced if len(results) == 0 and constructor_sliced is Series: result = constructor_sliced(results, dtype=np.float64) else: result = constructor_sliced(results) result.index = res_index
return result
def apply_str(self) -> DataFrame | Series: # Caller is responsible for checking isinstance(self.func, str) # TODO: GH#39993 - Avoid special-casing by replacing with lambda if self.func == "size": # Special-cased because DataFrame.size returns a single scalar obj = self.obj value = obj.shape[self.axis] return obj._constructor_sliced(value, index=self.agg_axis) return super().apply_str()
class FrameRowApply(FrameApply): axis: AxisInt = 0
@property def series_generator(self) -> Generator[Series, None, None]: return (self.obj._ixs(i, axis=1) for i in range(len(self.columns)))
@staticmethod @functools.cache def generate_numba_apply_func( func, nogil=True, nopython=True, parallel=False ) -> Callable[[npt.NDArray, Index, Index], dict[int, Any]]: numba = import_optional_dependency("numba") from pandas import Series
# Import helper from extensions to cast string object -> np strings # Note: This also has the side effect of loading our numba extensions from pandas.core._numba.extensions import maybe_cast_str
jitted_udf = numba.extending.register_jitable(func)
# Currently the parallel argument doesn't get passed through here # (it's disabled) since the dicts in numba aren't thread-safe. @numba.jit(nogil=nogil, nopython=nopython, parallel=parallel) def numba_func(values, col_names, df_index): results = {} for j in range(values.shape[1]): # Create the series ser = Series( values[:, j], index=df_index, name=maybe_cast_str(col_names[j]) ) results[j] = jitted_udf(ser) return results
return numba_func
def apply_with_numba(self) -> dict[int, Any]: nb_func = self.generate_numba_apply_func( cast(Callable, self.func), **self.engine_kwargs ) from pandas.core._numba.extensions import set_numba_data
index = self.obj.index if index.dtype == "string": index = index.astype(object)
columns = self.obj.columns if columns.dtype == "string": columns = columns.astype(object)
# Convert from numba dict to regular dict # Our isinstance checks in the df constructor don't pass for numbas typed dict with set_numba_data(index) as index, set_numba_data(columns) as columns: res = dict(nb_func(self.values, columns, index)) return res
@property def result_index(self) -> Index: return self.columns
@property def result_columns(self) -> Index: return self.index
def wrap_results_for_axis( self, results: ResType, res_index: Index ) -> DataFrame | Series: """return the results for the rows"""
if self.result_type == "reduce": # e.g. test_apply_dict GH#8735 res = self.obj._constructor_sliced(results) res.index = res_index return res
elif self.result_type is None and all( isinstance(x, dict) for x in results.values() ): # Our operation was a to_dict op e.g. # test_apply_dict GH#8735, test_apply_reduce_to_dict GH#25196 #37544 res = self.obj._constructor_sliced(results) res.index = res_index return res
try: result = self.obj._constructor(data=results) except ValueError as err: if "All arrays must be of the same length" in str(err): # e.g. result = [[2, 3], [1.5], ['foo', 'bar']] # see test_agg_listlike_result GH#29587 res = self.obj._constructor_sliced(results) res.index = res_index return res else: raise
if not isinstance(results[0], ABCSeries): if len(result.index) == len(self.res_columns): result.index = self.res_columns
if len(result.columns) == len(res_index): result.columns = res_index
return result
class FrameColumnApply(FrameApply): axis: AxisInt = 1
def apply_broadcast(self, target: DataFrame) -> DataFrame: result = super().apply_broadcast(target.T) return result.T
@property def series_generator(self) -> Generator[Series, None, None]: values = self.values values = ensure_wrapped_if_datetimelike(values) assert len(values) > 0
# We create one Series object, and will swap out the data inside # of it. Kids: don't do this at home. ser = self.obj._ixs(0, axis=0) mgr = ser._mgr
is_view = mgr.blocks[0].refs.has_reference() # type: ignore[union-attr]
if isinstance(ser.dtype, ExtensionDtype): # values will be incorrect for this block # TODO(EA2D): special case would be unnecessary with 2D EAs obj = self.obj for i in range(len(obj)): yield obj._ixs(i, axis=0)
else: for arr, name in zip(values, self.index): # GH#35462 re-pin mgr in case setitem changed it ser._mgr = mgr mgr.set_values(arr) object.__setattr__(ser, "_name", name) if not is_view: # In apply_series_generator we store the a shallow copy of the # result, which potentially increases the ref count of this reused # `ser` object (depending on the result of the applied function) # -> if that happened and `ser` is already a copy, then we reset # the refs here to avoid triggering a unnecessary CoW inside the # applied function (https://github.com/pandas-dev/pandas/pull/56212) mgr.blocks[0].refs = BlockValuesRefs(mgr.blocks[0]) # type: ignore[union-attr] yield ser
@staticmethod @functools.cache def generate_numba_apply_func( func, nogil=True, nopython=True, parallel=False ) -> Callable[[npt.NDArray, Index, Index], dict[int, Any]]: numba = import_optional_dependency("numba") from pandas import Series from pandas.core._numba.extensions import maybe_cast_str
jitted_udf = numba.extending.register_jitable(func)
@numba.jit(nogil=nogil, nopython=nopython, parallel=parallel) def numba_func(values, col_names_index, index): results = {} # Currently the parallel argument doesn't get passed through here # (it's disabled) since the dicts in numba aren't thread-safe. for i in range(values.shape[0]): # Create the series # TODO: values corrupted without the copy ser = Series( values[i].copy(), index=col_names_index, name=maybe_cast_str(index[i]), ) results[i] = jitted_udf(ser)
return results
return numba_func
def apply_with_numba(self) -> dict[int, Any]: nb_func = self.generate_numba_apply_func( cast(Callable, self.func), **self.engine_kwargs )
from pandas.core._numba.extensions import set_numba_data
# Convert from numba dict to regular dict # Our isinstance checks in the df constructor don't pass for numbas typed dict with set_numba_data(self.obj.index) as index, set_numba_data( self.columns ) as columns: res = dict(nb_func(self.values, columns, index))
return res
@property def result_index(self) -> Index: return self.index
@property def result_columns(self) -> Index: return self.columns
def wrap_results_for_axis( self, results: ResType, res_index: Index ) -> DataFrame | Series: """return the results for the columns""" result: DataFrame | Series
# we have requested to expand if self.result_type == "expand": result = self.infer_to_same_shape(results, res_index)
# we have a non-series and don't want inference elif not isinstance(results[0], ABCSeries): result = self.obj._constructor_sliced(results) result.index = res_index
# we may want to infer results else: result = self.infer_to_same_shape(results, res_index)
return result
def infer_to_same_shape(self, results: ResType, res_index: Index) -> DataFrame: """infer the results to the same shape as the input object""" result = self.obj._constructor(data=results) result = result.T
# set the index result.index = res_index
# infer dtypes result = result.infer_objects(copy=False)
return result
class SeriesApply(NDFrameApply): obj: Series axis: AxisInt = 0 by_row: Literal[False, "compat", "_compat"] # only relevant for apply()
def __init__( self, obj: Series, func: AggFuncType, *, convert_dtype: bool | lib.NoDefault = lib.no_default, by_row: Literal[False, "compat", "_compat"] = "compat", args, kwargs, ) -> None: if convert_dtype is lib.no_default: convert_dtype = True else: warnings.warn( "the convert_dtype parameter is deprecated and will be removed in a " "future version. Do ``ser.astype(object).apply()`` " "instead if you want ``convert_dtype=False``.", FutureWarning, stacklevel=find_stack_level(), ) self.convert_dtype = convert_dtype
super().__init__( obj, func, raw=False, result_type=None, by_row=by_row, args=args, kwargs=kwargs, )
def apply(self) -> DataFrame | Series: obj = self.obj
if len(obj) == 0: return self.apply_empty_result()
# dispatch to handle list-like or dict-like if is_list_like(self.func): return self.apply_list_or_dict_like()
if isinstance(self.func, str): # if we are a string, try to dispatch return self.apply_str()
if self.by_row == "_compat": return self.apply_compat()
# self.func is Callable return self.apply_standard()
def agg(self): result = super().agg() if result is None: obj = self.obj func = self.func # string, list-like, and dict-like are entirely handled in super assert callable(func)
# GH53325: The setup below is just to keep current behavior while emitting a # deprecation message. In the future this will all be replaced with a simple # `result = f(self.obj, *self.args, **self.kwargs)`. try: result = obj.apply(func, args=self.args, **self.kwargs) except (ValueError, AttributeError, TypeError): result = func(obj, *self.args, **self.kwargs) else: msg = ( f"using {func} in {type(obj).__name__}.agg cannot aggregate and " f"has been deprecated. Use {type(obj).__name__}.transform to " f"keep behavior unchanged." ) warnings.warn(msg, FutureWarning, stacklevel=find_stack_level())
return result
def apply_empty_result(self) -> Series: obj = self.obj return obj._constructor(dtype=obj.dtype, index=obj.index).__finalize__( obj, method="apply" )
def apply_compat(self): """compat apply method for funcs in listlikes and dictlikes.
Used for each callable when giving listlikes and dictlikes of callables to apply. Needed for compatibility with Pandas < v2.1.
.. versionadded:: 2.1.0 """ obj = self.obj func = self.func
if callable(func): f = com.get_cython_func(func) if f and not self.args and not self.kwargs: return obj.apply(func, by_row=False)
try: result = obj.apply(func, by_row="compat") except (ValueError, AttributeError, TypeError): result = obj.apply(func, by_row=False) return result
def apply_standard(self) -> DataFrame | Series: # caller is responsible for ensuring that f is Callable func = cast(Callable, self.func) obj = self.obj
if isinstance(func, np.ufunc): with np.errstate(all="ignore"): return func(obj, *self.args, **self.kwargs) elif not self.by_row: return func(obj, *self.args, **self.kwargs)
if self.args or self.kwargs: # _map_values does not support args/kwargs def curried(x): return func(x, *self.args, **self.kwargs)
else: curried = func
# row-wise access # apply doesn't have a `na_action` keyword and for backward compat reasons # we need to give `na_action="ignore"` for categorical data. # TODO: remove the `na_action="ignore"` when that default has been changed in # Categorical (GH51645). action = "ignore" if isinstance(obj.dtype, CategoricalDtype) else None mapped = obj._map_values( mapper=curried, na_action=action, convert=self.convert_dtype )
if len(mapped) and isinstance(mapped[0], ABCSeries): # GH#43986 Need to do list(mapped) in order to get treated as nested # See also GH#25959 regarding EA support return obj._constructor_expanddim(list(mapped), index=obj.index) else: return obj._constructor(mapped, index=obj.index).__finalize__( obj, method="apply" )
class GroupByApply(Apply): obj: GroupBy | Resampler | BaseWindow
def __init__( self, obj: GroupBy[NDFrameT], func: AggFuncType, *, args, kwargs, ) -> None: kwargs = kwargs.copy() self.axis = obj.obj._get_axis_number(kwargs.get("axis", 0)) super().__init__( obj, func, raw=False, result_type=None, args=args, kwargs=kwargs, )
def apply(self): raise NotImplementedError
def transform(self): raise NotImplementedError
def agg_or_apply_list_like( self, op_name: Literal["agg", "apply"] ) -> DataFrame | Series: obj = self.obj kwargs = self.kwargs if op_name == "apply": kwargs = {**kwargs, "by_row": False}
if getattr(obj, "axis", 0) == 1: raise NotImplementedError("axis other than 0 is not supported")
if obj._selected_obj.ndim == 1: # For SeriesGroupBy this matches _obj_with_exclusions selected_obj = obj._selected_obj else: selected_obj = obj._obj_with_exclusions
# Only set as_index=True on groupby objects, not Window or Resample # that inherit from this class. with com.temp_setattr( obj, "as_index", True, condition=hasattr(obj, "as_index") ): keys, results = self.compute_list_like(op_name, selected_obj, kwargs) result = self.wrap_results_list_like(keys, results) return result
def agg_or_apply_dict_like( self, op_name: Literal["agg", "apply"] ) -> DataFrame | Series: from pandas.core.groupby.generic import ( DataFrameGroupBy, SeriesGroupBy, )
assert op_name in ["agg", "apply"]
obj = self.obj kwargs = {} if op_name == "apply": by_row = "_compat" if self.by_row else False kwargs.update({"by_row": by_row})
if getattr(obj, "axis", 0) == 1: raise NotImplementedError("axis other than 0 is not supported")
selected_obj = obj._selected_obj selection = obj._selection
is_groupby = isinstance(obj, (DataFrameGroupBy, SeriesGroupBy))
# Numba Groupby engine/engine-kwargs passthrough if is_groupby: engine = self.kwargs.get("engine", None) engine_kwargs = self.kwargs.get("engine_kwargs", None) kwargs.update({"engine": engine, "engine_kwargs": engine_kwargs})
with com.temp_setattr( obj, "as_index", True, condition=hasattr(obj, "as_index") ): result_index, result_data = self.compute_dict_like( op_name, selected_obj, selection, kwargs ) result = self.wrap_results_dict_like(selected_obj, result_index, result_data) return result
class ResamplerWindowApply(GroupByApply): axis: AxisInt = 0 obj: Resampler | BaseWindow
def __init__( self, obj: Resampler | BaseWindow, func: AggFuncType, *, args, kwargs, ) -> None: super(GroupByApply, self).__init__( obj, func, raw=False, result_type=None, args=args, kwargs=kwargs, )
def apply(self): raise NotImplementedError
def transform(self): raise NotImplementedError
def reconstruct_func( func: AggFuncType | None, **kwargs) -> tuple[bool, AggFuncType, tuple[str, ...] | None, npt.NDArray[np.intp] | None]: """ This is the internal function to reconstruct func given if there is relabeling or not and also normalize the keyword to get new order of columns.
If named aggregation is applied, `func` will be None, and kwargs contains the column and aggregation function information to be parsed; If named aggregation is not applied, `func` is either string (e.g. 'min') or Callable, or list of them (e.g. ['min', np.max]), or the dictionary of column name and str/Callable/list of them (e.g. {'A': 'min'}, or {'A': [np.min, lambda x: x]})
If relabeling is True, will return relabeling, reconstructed func, column names, and the reconstructed order of columns. If relabeling is False, the columns and order will be None.
Parameters ---------- func: agg function (e.g. 'min' or Callable) or list of agg functions (e.g. ['min', np.max]) or dictionary (e.g. {'A': ['min', np.max]}). **kwargs: dict, kwargs used in is_multi_agg_with_relabel and normalize_keyword_aggregation function for relabelling
Returns ------- relabelling: bool, if there is relabelling or not func: normalized and mangled func columns: tuple of column names order: array of columns indices
Examples -------- >>> reconstruct_func(None, **{"foo": ("col", "min")}) (True, defaultdict(<class 'list'>, {'col': ['min']}), ('foo',), array([0]))
>>> reconstruct_func("min") (False, 'min', None, None) """ relabeling = func is None and is_multi_agg_with_relabel(**kwargs) columns: tuple[str, ...] | None = None order: npt.NDArray[np.intp] | None = None
if not relabeling: if isinstance(func, list) and len(func) > len(set(func)): # GH 28426 will raise error if duplicated function names are used and # there is no reassigned name raise SpecificationError( "Function names must be unique if there is no new column names " "assigned" ) if func is None: # nicer error message raise TypeError("Must provide 'func' or tuples of '(column, aggfunc).")
if relabeling: # error: Incompatible types in assignment (expression has type # "MutableMapping[Hashable, list[Callable[..., Any] | str]]", variable has type # "Callable[..., Any] | str | list[Callable[..., Any] | str] | # MutableMapping[Hashable, Callable[..., Any] | str | list[Callable[..., Any] | # str]] | None") func, columns, order = normalize_keyword_aggregation( # type: ignore[assignment] kwargs ) assert func is not None
return relabeling, func, columns, order
def is_multi_agg_with_relabel(**kwargs) -> bool: """ Check whether kwargs passed to .agg look like multi-agg with relabeling.
Parameters ---------- **kwargs : dict
Returns ------- bool
Examples -------- >>> is_multi_agg_with_relabel(a="max") False >>> is_multi_agg_with_relabel(a_max=("a", "max"), a_min=("a", "min")) True >>> is_multi_agg_with_relabel() False """ return all(isinstance(v, tuple) and len(v) == 2 for v in kwargs.values()) and ( len(kwargs) > 0 )
def normalize_keyword_aggregation( kwargs: dict,) -> tuple[ MutableMapping[Hashable, list[AggFuncTypeBase]], tuple[str, ...], npt.NDArray[np.intp],]: """ Normalize user-provided "named aggregation" kwargs. Transforms from the new ``Mapping[str, NamedAgg]`` style kwargs to the old Dict[str, List[scalar]]].
Parameters ---------- kwargs : dict
Returns ------- aggspec : dict The transformed kwargs. columns : tuple[str, ...] The user-provided keys. col_idx_order : List[int] List of columns indices.
Examples -------- >>> normalize_keyword_aggregation({"output": ("input", "sum")}) (defaultdict(<class 'list'>, {'input': ['sum']}), ('output',), array([0])) """ from pandas.core.indexes.base import Index
# Normalize the aggregation functions as Mapping[column, List[func]], # process normally, then fixup the names. # TODO: aggspec type: typing.Dict[str, List[AggScalar]] aggspec = defaultdict(list) order = [] columns, pairs = list(zip(*kwargs.items()))
for column, aggfunc in pairs: aggspec[column].append(aggfunc) order.append((column, com.get_callable_name(aggfunc) or aggfunc))
# uniquify aggfunc name if duplicated in order list uniquified_order = _make_unique_kwarg_list(order)
# GH 25719, due to aggspec will change the order of assigned columns in aggregation # uniquified_aggspec will store uniquified order list and will compare it with order # based on index aggspec_order = [ (column, com.get_callable_name(aggfunc) or aggfunc) for column, aggfuncs in aggspec.items() for aggfunc in aggfuncs ] uniquified_aggspec = _make_unique_kwarg_list(aggspec_order)
# get the new index of columns by comparison col_idx_order = Index(uniquified_aggspec).get_indexer(uniquified_order) return aggspec, columns, col_idx_order
def _make_unique_kwarg_list( seq: Sequence[tuple[Any, Any]]) -> Sequence[tuple[Any, Any]]: """ Uniquify aggfunc name of the pairs in the order list
Examples: -------- >>> kwarg_list = [('a', '<lambda>'), ('a', '<lambda>'), ('b', '<lambda>')] >>> _make_unique_kwarg_list(kwarg_list) [('a', '<lambda>_0'), ('a', '<lambda>_1'), ('b', '<lambda>')] """ return [ (pair[0], f"{pair[1]}_{seq[:i].count(pair)}") if seq.count(pair) > 1 else pair for i, pair in enumerate(seq) ]
def relabel_result( result: DataFrame | Series, func: dict[str, list[Callable | str]], columns: Iterable[Hashable], order: Iterable[int],) -> dict[Hashable, Series]: """ Internal function to reorder result if relabelling is True for dataframe.agg, and return the reordered result in dict.
Parameters: ---------- result: Result from aggregation func: Dict of (column name, funcs) columns: New columns name for relabelling order: New order for relabelling
Examples -------- >>> from pandas.core.apply import relabel_result >>> result = pd.DataFrame( ... {"A": [np.nan, 2, np.nan], "C": [6, np.nan, np.nan], "B": [np.nan, 4, 2.5]}, ... index=["max", "mean", "min"] ... ) >>> funcs = {"A": ["max"], "C": ["max"], "B": ["mean", "min"]} >>> columns = ("foo", "aab", "bar", "dat") >>> order = [0, 1, 2, 3] >>> result_in_dict = relabel_result(result, funcs, columns, order) >>> pd.DataFrame(result_in_dict, index=columns) A C B foo 2.0 NaN NaN aab NaN 6.0 NaN bar NaN NaN 4.0 dat NaN NaN 2.5 """ from pandas.core.indexes.base import Index
reordered_indexes = [ pair[0] for pair in sorted(zip(columns, order), key=lambda t: t[1]) ] reordered_result_in_dict: dict[Hashable, Series] = {} idx = 0
reorder_mask = not isinstance(result, ABCSeries) and len(result.columns) > 1 for col, fun in func.items(): s = result[col].dropna()
# In the `_aggregate`, the callable names are obtained and used in `result`, and # these names are ordered alphabetically. e.g. # C2 C1 # <lambda> 1 NaN # amax NaN 4.0 # max NaN 4.0 # sum 18.0 6.0 # Therefore, the order of functions for each column could be shuffled # accordingly so need to get the callable name if it is not parsed names, and # reorder the aggregated result for each column. # e.g. if df.agg(c1=("C2", sum), c2=("C2", lambda x: min(x))), correct order is # [sum, <lambda>], but in `result`, it will be [<lambda>, sum], and we need to # reorder so that aggregated values map to their functions regarding the order.
# However there is only one column being used for aggregation, not need to # reorder since the index is not sorted, and keep as is in `funcs`, e.g. # A # min 1.0 # mean 1.5 # mean 1.5 if reorder_mask: fun = [ com.get_callable_name(f) if not isinstance(f, str) else f for f in fun ] col_idx_order = Index(s.index).get_indexer(fun) s = s.iloc[col_idx_order]
# assign the new user-provided "named aggregation" as index names, and reindex # it based on the whole user-provided names. s.index = reordered_indexes[idx : idx + len(fun)] reordered_result_in_dict[col] = s.reindex(columns, copy=False) idx = idx + len(fun) return reordered_result_in_dict
def reconstruct_and_relabel_result(result, func, **kwargs) -> DataFrame | Series: from pandas import DataFrame
relabeling, func, columns, order = reconstruct_func(func, **kwargs)
if relabeling: # This is to keep the order to columns occurrence unchanged, and also # keep the order of new columns occurrence unchanged
# For the return values of reconstruct_func, if relabeling is # False, columns and order will be None. assert columns is not None assert order is not None
result_in_dict = relabel_result(result, func, columns, order) result = DataFrame(result_in_dict, index=columns)
return result
# TODO: Can't use, because mypy doesn't like us setting __name__# error: "partial[Any]" has no attribute "__name__"# the type is:# typing.Sequence[Callable[..., ScalarResult]]# -> typing.Sequence[Callable[..., ScalarResult]]:
def _managle_lambda_list(aggfuncs: Sequence[Any]) -> Sequence[Any]: """ Possibly mangle a list of aggfuncs.
Parameters ---------- aggfuncs : Sequence
Returns ------- mangled: list-like A new AggSpec sequence, where lambdas have been converted to have unique names.
Notes ----- If just one aggfunc is passed, the name will not be mangled. """ if len(aggfuncs) <= 1: # don't mangle for .agg([lambda x: .]) return aggfuncs i = 0 mangled_aggfuncs = [] for aggfunc in aggfuncs: if com.get_callable_name(aggfunc) == "<lambda>": aggfunc = partial(aggfunc) aggfunc.__name__ = f"<lambda_{i}>" i += 1 mangled_aggfuncs.append(aggfunc)
return mangled_aggfuncs
def maybe_mangle_lambdas(agg_spec: Any) -> Any: """ Make new lambdas with unique names.
Parameters ---------- agg_spec : Any An argument to GroupBy.agg. Non-dict-like `agg_spec` are pass through as is. For dict-like `agg_spec` a new spec is returned with name-mangled lambdas.
Returns ------- mangled : Any Same type as the input.
Examples -------- >>> maybe_mangle_lambdas('sum') 'sum' >>> maybe_mangle_lambdas([lambda: 1, lambda: 2]) # doctest: +SKIP [<function __main__.<lambda_0>, <function pandas...._make_lambda.<locals>.f(*args, **kwargs)>] """ is_dict = is_dict_like(agg_spec) if not (is_dict or is_list_like(agg_spec)): return agg_spec mangled_aggspec = type(agg_spec)() # dict or OrderedDict
if is_dict: for key, aggfuncs in agg_spec.items(): if is_list_like(aggfuncs) and not is_dict_like(aggfuncs): mangled_aggfuncs = _managle_lambda_list(aggfuncs) else: mangled_aggfuncs = aggfuncs
mangled_aggspec[key] = mangled_aggfuncs else: mangled_aggspec = _managle_lambda_list(agg_spec)
return mangled_aggspec
def validate_func_kwargs( kwargs: dict,) -> tuple[list[str], list[str | Callable[..., Any]]]: """ Validates types of user-provided "named aggregation" kwargs. `TypeError` is raised if aggfunc is not `str` or callable.
Parameters ---------- kwargs : dict
Returns ------- columns : List[str] List of user-provided keys. func : List[Union[str, callable[...,Any]]] List of user-provided aggfuncs
Examples -------- >>> validate_func_kwargs({'one': 'min', 'two': 'max'}) (['one', 'two'], ['min', 'max']) """ tuple_given_message = "func is expected but received {} in **kwargs." columns = list(kwargs) func = [] for col_func in kwargs.values(): if not (isinstance(col_func, str) or callable(col_func)): raise TypeError(tuple_given_message.format(type(col_func).__name__)) func.append(col_func) if not columns: no_arg_message = "Must provide 'func' or named aggregation **kwargs." raise TypeError(no_arg_message) return columns, func
def include_axis(op_name: Literal["agg", "apply"], colg: Series | DataFrame) -> bool: return isinstance(colg, ABCDataFrame) or ( isinstance(colg, ABCSeries) and op_name == "agg" )
def warn_alias_replacement( obj: AggObjType, func: Callable, alias: str,) -> None: if alias.startswith("np."): full_alias = alias else: full_alias = f"{type(obj).__name__}.{alias}" alias = f'"{alias}"' warnings.warn( f"The provided callable {func} is currently using " f"{full_alias}. In a future version of pandas, " f"the provided callable will be used directly. To keep current " f"behavior pass the string {alias} instead.", category=FutureWarning, stacklevel=find_stack_level(), )123456789"""core.array_algos is for algorithms that operate on ndarray and ExtensionArray.These should:
- Assume that any Index, Series, or DataFrame objects have already been unwrapped.- Assume that any list arguments have already been cast to ndarray/EA.- Not depend on Index, Series, or DataFrame, nor import any of these.- May dispatch to ExtensionArray methods, but should not import from core.arrays."""12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667"""datetimelke_accumulations.py is for accumulations of datetimelike extension arrays"""
from __future__ import annotations
from typing import Callable
import numpy as np
from pandas._libs import iNaT
from pandas.core.dtypes.missing import isna
def _cum_func( func: Callable, values: np.ndarray, *, skipna: bool = True,): """ Accumulations for 1D datetimelike arrays.
Parameters ---------- func : np.cumsum, np.maximum.accumulate, np.minimum.accumulate values : np.ndarray Numpy array with the values (can be of any dtype that support the operation). Values is changed is modified inplace. skipna : bool, default True Whether to skip NA. """ try: fill_value = { np.maximum.accumulate: np.iinfo(np.int64).min, np.cumsum: 0, np.minimum.accumulate: np.iinfo(np.int64).max, }[func] except KeyError: raise ValueError(f"No accumulation for {func} implemented on BaseMaskedArray")
mask = isna(values) y = values.view("i8") y[mask] = fill_value
if not skipna: mask = np.maximum.accumulate(mask)
result = func(y) result[mask] = iNaT
if values.dtype.kind in "mM": return result.view(values.dtype.base) return result
def cumsum(values: np.ndarray, *, skipna: bool = True) -> np.ndarray: return _cum_func(np.cumsum, values, skipna=skipna)
def cummin(values: np.ndarray, *, skipna: bool = True): return _cum_func(np.minimum.accumulate, values, skipna=skipna)
def cummax(values: np.ndarray, *, skipna: bool = True): return _cum_func(np.maximum.accumulate, values, skipna=skipna)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990"""masked_accumulations.py is for accumulation algorithms using a mask-based approachfor missing values."""
from __future__ import annotations
from typing import ( TYPE_CHECKING, Callable,)
import numpy as np
if TYPE_CHECKING: from pandas._typing import npt
def _cum_func( func: Callable, values: np.ndarray, mask: npt.NDArray[np.bool_], *, skipna: bool = True,): """ Accumulations for 1D masked array.
We will modify values in place to replace NAs with the appropriate fill value.
Parameters ---------- func : np.cumsum, np.cumprod, np.maximum.accumulate, np.minimum.accumulate values : np.ndarray Numpy array with the values (can be of any dtype that support the operation). mask : np.ndarray Boolean numpy array (True values indicate missing values). skipna : bool, default True Whether to skip NA. """ dtype_info: np.iinfo | np.finfo if values.dtype.kind == "f": dtype_info = np.finfo(values.dtype.type) elif values.dtype.kind in "iu": dtype_info = np.iinfo(values.dtype.type) elif values.dtype.kind == "b": # Max value of bool is 1, but since we are setting into a boolean # array, 255 is fine as well. Min value has to be 0 when setting # into the boolean array. dtype_info = np.iinfo(np.uint8) else: raise NotImplementedError( f"No masked accumulation defined for dtype {values.dtype.type}" ) try: fill_value = { np.cumprod: 1, np.maximum.accumulate: dtype_info.min, np.cumsum: 0, np.minimum.accumulate: dtype_info.max, }[func] except KeyError: raise NotImplementedError( f"No accumulation for {func} implemented on BaseMaskedArray" )
values[mask] = fill_value
if not skipna: mask = np.maximum.accumulate(mask)
values = func(values) return values, mask
def cumsum(values: np.ndarray, mask: npt.NDArray[np.bool_], *, skipna: bool = True): return _cum_func(np.cumsum, values, mask, skipna=skipna)
def cumprod(values: np.ndarray, mask: npt.NDArray[np.bool_], *, skipna: bool = True): return _cum_func(np.cumprod, values, mask, skipna=skipna)
def cummin(values: np.ndarray, mask: npt.NDArray[np.bool_], *, skipna: bool = True): return _cum_func(np.minimum.accumulate, values, mask, skipna=skipna)
def cummax(values: np.ndarray, mask: npt.NDArray[np.bool_], *, skipna: bool = True): return _cum_func(np.maximum.accumulate, values, mask, skipna=skipna)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197"""masked_reductions.py is for reduction algorithms using a mask-based approachfor missing values."""from __future__ import annotations
from typing import ( TYPE_CHECKING, Callable,)import warnings
import numpy as np
from pandas._libs import missing as libmissing
from pandas.core.nanops import check_below_min_count
if TYPE_CHECKING: from pandas._typing import ( AxisInt, npt, )
def _reductions( func: Callable, values: np.ndarray, mask: npt.NDArray[np.bool_], *, skipna: bool = True, min_count: int = 0, axis: AxisInt | None = None, **kwargs,): """ Sum, mean or product for 1D masked array.
Parameters ---------- func : np.sum or np.prod values : np.ndarray Numpy array with the values (can be of any dtype that support the operation). mask : np.ndarray[bool] Boolean numpy array (True values indicate missing values). skipna : bool, default True Whether to skip NA. min_count : int, default 0 The required number of valid values to perform the operation. If fewer than ``min_count`` non-NA values are present the result will be NA. axis : int, optional, default None """ if not skipna: if mask.any() or check_below_min_count(values.shape, None, min_count): return libmissing.NA else: return func(values, axis=axis, **kwargs) else: if check_below_min_count(values.shape, mask, min_count) and ( axis is None or values.ndim == 1 ): return libmissing.NA
return func(values, where=~mask, axis=axis, **kwargs)
def sum( values: np.ndarray, mask: npt.NDArray[np.bool_], *, skipna: bool = True, min_count: int = 0, axis: AxisInt | None = None,): return _reductions( np.sum, values=values, mask=mask, skipna=skipna, min_count=min_count, axis=axis )
def prod( values: np.ndarray, mask: npt.NDArray[np.bool_], *, skipna: bool = True, min_count: int = 0, axis: AxisInt | None = None,): return _reductions( np.prod, values=values, mask=mask, skipna=skipna, min_count=min_count, axis=axis )
def _minmax( func: Callable, values: np.ndarray, mask: npt.NDArray[np.bool_], *, skipna: bool = True, axis: AxisInt | None = None,): """ Reduction for 1D masked array.
Parameters ---------- func : np.min or np.max values : np.ndarray Numpy array with the values (can be of any dtype that support the operation). mask : np.ndarray[bool] Boolean numpy array (True values indicate missing values). skipna : bool, default True Whether to skip NA. axis : int, optional, default None """ if not skipna: if mask.any() or not values.size: # min/max with empty array raise in numpy, pandas returns NA return libmissing.NA else: return func(values, axis=axis) else: subset = values[~mask] if subset.size: return func(subset, axis=axis) else: # min/max with empty array raise in numpy, pandas returns NA return libmissing.NA
def min( values: np.ndarray, mask: npt.NDArray[np.bool_], *, skipna: bool = True, axis: AxisInt | None = None,): return _minmax(np.min, values=values, mask=mask, skipna=skipna, axis=axis)
def max( values: np.ndarray, mask: npt.NDArray[np.bool_], *, skipna: bool = True, axis: AxisInt | None = None,): return _minmax(np.max, values=values, mask=mask, skipna=skipna, axis=axis)
def mean( values: np.ndarray, mask: npt.NDArray[np.bool_], *, skipna: bool = True, axis: AxisInt | None = None,): if not values.size or mask.all(): return libmissing.NA return _reductions(np.mean, values=values, mask=mask, skipna=skipna, axis=axis)
def var( values: np.ndarray, mask: npt.NDArray[np.bool_], *, skipna: bool = True, axis: AxisInt | None = None, ddof: int = 1,): if not values.size or mask.all(): return libmissing.NA
with warnings.catch_warnings(): warnings.simplefilter("ignore", RuntimeWarning) return _reductions( np.var, values=values, mask=mask, skipna=skipna, axis=axis, ddof=ddof )
def std( values: np.ndarray, mask: npt.NDArray[np.bool_], *, skipna: bool = True, axis: AxisInt | None = None, ddof: int = 1,): if not values.size or mask.all(): return libmissing.NA
with warnings.catch_warnings(): warnings.simplefilter("ignore", RuntimeWarning) return _reductions( np.std, values=values, mask=mask, skipna=skipna, axis=axis, ddof=ddof )lib/python3.12/site-packages/pandas/_libs/__init__.pyAdded+27
lib/python3.12/site-packages/pandas/_libs/algos.pyiAdded+416
lib/python3.12/site-packages/pandas/_libs/arrays.pyiAdded+40
lib/python3.12/site-packages/pandas/_libs/byteswap.cpython-312-x86_64-linux-gnu.soAdded
lib/python3.12/site-packages/pandas/_libs/byteswap.pyiAdded+5
lib/python3.12/site-packages/pandas/_libs/groupby.pyiAdded+216
lib/python3.12/site-packages/pandas/_libs/hashing.pyiAdded+9
lib/python3.12/site-packages/pandas/_libs/hashtable.pyiAdded+252
lib/python3.12/site-packages/pandas/_libs/index.pyiAdded+100
lib/python3.12/site-packages/pandas/_libs/indexing.cpython-312-x86_64-linux-gnu.soAdded
lib/python3.12/site-packages/pandas/_libs/indexing.pyiAdded+17
lib/python3.12/site-packages/pandas/_libs/internals.pyiAdded+94
lib/python3.12/site-packages/pandas/_libs/interval.pyiAdded+174
lib/python3.12/site-packages/pandas/_libs/join.pyiAdded+79
lib/python3.12/site-packages/pandas/_libs/json.cpython-312-x86_64-linux-gnu.soAdded
lib/python3.12/site-packages/pandas/_libs/json.pyiAdded+23
lib/python3.12/site-packages/pandas/_libs/lib.pyiAdded+213
lib/python3.12/site-packages/pandas/_libs/missing.pyiAdded+16
lib/python3.12/site-packages/pandas/_libs/ops.pyiAdded+51
lib/python3.12/site-packages/pandas/_libs/ops_dispatch.cpython-312-x86_64-linux-gnu.soAdded
lib/python3.12/site-packages/pandas/_libs/ops_dispatch.pyiAdded+5
lib/python3.12/site-packages/pandas/_libs/pandas_datetime.cpython-312-x86_64-linux-gnu.soAdded
lib/python3.12/site-packages/pandas/_libs/pandas_parser.cpython-312-x86_64-linux-gnu.soAdded
lib/python3.12/site-packages/pandas/_libs/parsers.pyiAdded+77
lib/python3.12/site-packages/pandas/_libs/properties.cpython-312-x86_64-linux-gnu.soAdded
lib/python3.12/site-packages/pandas/_libs/properties.pyiAdded+27
lib/python3.12/site-packages/pandas/_libs/reshape.pyiAdded+16
lib/python3.12/site-packages/pandas/_libs/sas.pyiAdded+7
lib/python3.12/site-packages/pandas/_libs/sparse.pyiAdded+51
lib/python3.12/site-packages/pandas/_libs/testing.pyiAdded+12
lib/python3.12/site-packages/pandas/_libs/tslib.pyiAdded+37
lib/python3.12/site-packages/pandas/_libs/writers.pyiAdded+20
lib/python3.12/site-packages/pandas/core/__init__.pyAdded
lib/python3.12/site-packages/pandas/core/accessor.pyAdded+340
lib/python3.12/site-packages/pandas/core/algorithms.pyAdded+1747
lib/python3.12/site-packages/pandas/core/api.pyAdded+140
lib/python3.12/site-packages/pandas/core/apply.pyAdded+2062
lib/python3.12/site-packages/pandas/core/array_algos/__init__.pyAdded+9
lib/python3.12/site-packages/pandas/core/array_algos/__pycache__/__init__.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/core/array_algos/__pycache__/datetimelike_accumulations.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/core/array_algos/__pycache__/masked_accumulations.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/core/array_algos/__pycache__/masked_reductions.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/core/array_algos/__pycache__/putmask.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/core/array_algos/__pycache__/quantile.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/core/array_algos/__pycache__/replace.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/core/array_algos/__pycache__/take.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/core/array_algos/__pycache__/transforms.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/core/array_algos/datetimelike_accumulations.pyAdded+67
lib/python3.12/site-packages/pandas/core/array_algos/masked_accumulations.pyAdded+90
lib/python3.12/site-packages/pandas/core/array_algos/masked_reductions.pyAdded+197