|
| 1 | +# Copyright 2021 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +from typing import Any, Optional, Sequence |
| 16 | + |
| 17 | +import numpy |
| 18 | +import pandas |
| 19 | +from pandas._libs import NaT |
| 20 | +from pandas._typing import Scalar |
| 21 | +import pandas.compat.numpy.function |
| 22 | +import pandas.core.algorithms |
| 23 | +import pandas.core.arrays |
| 24 | +import pandas.core.dtypes.base |
| 25 | +from pandas.core.dtypes.common import is_dtype_equal, is_list_like, pandas_dtype |
| 26 | +import pandas.core.dtypes.dtypes |
| 27 | +import pandas.core.dtypes.generic |
| 28 | +import pandas.core.nanops |
| 29 | + |
| 30 | +from db_dtypes import pandas_backports |
| 31 | + |
| 32 | + |
| 33 | +pandas_release = pandas_backports.pandas_release |
| 34 | + |
| 35 | + |
| 36 | +class BaseDatetimeDtype(pandas.core.dtypes.base.ExtensionDtype): |
| 37 | + na_value = NaT |
| 38 | + kind = "o" |
| 39 | + names = None |
| 40 | + |
| 41 | + @classmethod |
| 42 | + def construct_from_string(cls, name): |
| 43 | + if name != cls.name: |
| 44 | + raise TypeError() |
| 45 | + |
| 46 | + return cls() |
| 47 | + |
| 48 | + |
| 49 | +class BaseDatetimeArray( |
| 50 | + pandas_backports.OpsMixin, pandas_backports.NDArrayBackedExtensionArray |
| 51 | +): |
| 52 | + def __init__(self, values, dtype=None, copy: bool = False): |
| 53 | + if not ( |
| 54 | + isinstance(values, numpy.ndarray) and values.dtype == numpy.dtype("<M8[ns]") |
| 55 | + ): |
| 56 | + values = self.__ndarray(values) |
| 57 | + elif copy: |
| 58 | + values = values.copy() |
| 59 | + |
| 60 | + super().__init__(values=values, dtype=values.dtype) |
| 61 | + |
| 62 | + @classmethod |
| 63 | + def __ndarray(cls, scalars): |
| 64 | + return numpy.array( |
| 65 | + [None if scalar is None else cls._datetime(scalar) for scalar in scalars], |
| 66 | + "M8[ns]", |
| 67 | + ) |
| 68 | + |
| 69 | + @classmethod |
| 70 | + def _from_sequence(cls, scalars, *, dtype=None, copy=False): |
| 71 | + if dtype is not None: |
| 72 | + assert dtype.__class__ is cls.dtype.__class__ |
| 73 | + return cls(cls.__ndarray(scalars)) |
| 74 | + |
| 75 | + _from_sequence_of_strings = _from_sequence |
| 76 | + |
| 77 | + def astype(self, dtype, copy=True): |
| 78 | + dtype = pandas_dtype(dtype) |
| 79 | + if is_dtype_equal(dtype, self.dtype): |
| 80 | + if not copy: |
| 81 | + return self |
| 82 | + else: |
| 83 | + return self.copy() |
| 84 | + |
| 85 | + return super().astype(dtype, copy=copy) |
| 86 | + |
| 87 | + def _cmp_method(self, other, op): |
| 88 | + if type(other) != type(self): |
| 89 | + return NotImplemented |
| 90 | + return op(self._ndarray, other._ndarray) |
| 91 | + |
| 92 | + def __setitem__(self, key, value): |
| 93 | + if is_list_like(value): |
| 94 | + _datetime = self._datetime |
| 95 | + value = [_datetime(v) for v in value] |
| 96 | + elif not pandas.isna(value): |
| 97 | + value = self._datetime(value) |
| 98 | + return super().__setitem__(key, value) |
| 99 | + |
| 100 | + def _from_factorized(self, unique, original): |
| 101 | + return self.__class__(unique) |
| 102 | + |
| 103 | + def isna(self): |
| 104 | + return pandas.isna(self._ndarray) |
| 105 | + |
| 106 | + def _validate_scalar(self, value): |
| 107 | + if pandas.isna(value): |
| 108 | + return None |
| 109 | + |
| 110 | + if not isinstance(value, self.dtype.type): |
| 111 | + raise ValueError(value) |
| 112 | + |
| 113 | + return value |
| 114 | + |
| 115 | + def take( |
| 116 | + self, |
| 117 | + indices: Sequence[int], |
| 118 | + *, |
| 119 | + allow_fill: bool = False, |
| 120 | + fill_value: Any = None, |
| 121 | + ): |
| 122 | + indices = numpy.asarray(indices, dtype=numpy.intp) |
| 123 | + data = self._ndarray |
| 124 | + if allow_fill: |
| 125 | + fill_value = self._validate_scalar(fill_value) |
| 126 | + fill_value = ( |
| 127 | + numpy.datetime64() |
| 128 | + if fill_value is None |
| 129 | + else numpy.datetime64(self._datetime(fill_value)) |
| 130 | + ) |
| 131 | + if (indices < -1).any(): |
| 132 | + raise ValueError( |
| 133 | + "take called with negative indexes other than -1," |
| 134 | + " when a fill value is provided." |
| 135 | + ) |
| 136 | + out = data.take(indices) |
| 137 | + if allow_fill: |
| 138 | + out[indices == -1] = fill_value |
| 139 | + |
| 140 | + return self.__class__(out) |
| 141 | + |
| 142 | + # TODO: provide implementations of dropna, fillna, unique, |
| 143 | + # factorize, argsort, searchsoeted for better performance over |
| 144 | + # abstract implementations. |
| 145 | + |
| 146 | + def any( |
| 147 | + self, |
| 148 | + *, |
| 149 | + axis: Optional[int] = None, |
| 150 | + out=None, |
| 151 | + keepdims: bool = False, |
| 152 | + skipna: bool = True, |
| 153 | + ): |
| 154 | + pandas.compat.numpy.function.validate_any( |
| 155 | + (), {"out": out, "keepdims": keepdims} |
| 156 | + ) |
| 157 | + result = pandas.core.nanops.nanany(self._ndarray, axis=axis, skipna=skipna) |
| 158 | + return result |
| 159 | + |
| 160 | + def all( |
| 161 | + self, |
| 162 | + *, |
| 163 | + axis: Optional[int] = None, |
| 164 | + out=None, |
| 165 | + keepdims: bool = False, |
| 166 | + skipna: bool = True, |
| 167 | + ): |
| 168 | + pandas.compat.numpy.function.validate_all( |
| 169 | + (), {"out": out, "keepdims": keepdims} |
| 170 | + ) |
| 171 | + result = pandas.core.nanops.nanall(self._ndarray, axis=axis, skipna=skipna) |
| 172 | + return result |
| 173 | + |
| 174 | + def min( |
| 175 | + self, *, axis: Optional[int] = None, skipna: bool = True, **kwargs |
| 176 | + ) -> Scalar: |
| 177 | + pandas.compat.numpy.function.validate_min((), kwargs) |
| 178 | + result = pandas.core.nanops.nanmin( |
| 179 | + values=self._ndarray, axis=axis, mask=self.isna(), skipna=skipna |
| 180 | + ) |
| 181 | + return self._box_func(result) |
| 182 | + |
| 183 | + def max( |
| 184 | + self, *, axis: Optional[int] = None, skipna: bool = True, **kwargs |
| 185 | + ) -> Scalar: |
| 186 | + pandas.compat.numpy.function.validate_max((), kwargs) |
| 187 | + result = pandas.core.nanops.nanmax( |
| 188 | + values=self._ndarray, axis=axis, mask=self.isna(), skipna=skipna |
| 189 | + ) |
| 190 | + return self._box_func(result) |
| 191 | + |
| 192 | + if pandas_release >= (1, 2): |
| 193 | + |
| 194 | + def median( |
| 195 | + self, |
| 196 | + *, |
| 197 | + axis: Optional[int] = None, |
| 198 | + out=None, |
| 199 | + overwrite_input: bool = False, |
| 200 | + keepdims: bool = False, |
| 201 | + skipna: bool = True, |
| 202 | + ): |
| 203 | + pandas.compat.numpy.function.validate_median( |
| 204 | + (), |
| 205 | + {"out": out, "overwrite_input": overwrite_input, "keepdims": keepdims}, |
| 206 | + ) |
| 207 | + result = pandas.core.nanops.nanmedian( |
| 208 | + self._ndarray, axis=axis, skipna=skipna |
| 209 | + ) |
| 210 | + return self._box_func(result) |
0 commit comments