|
| 1 | +"""An interface for extending pandas with custom arrays.""" |
| 2 | +import abc |
| 3 | +from typing import Tuple, Sequence, Optional, Any # noqa |
| 4 | + |
| 5 | +import numpy as np |
| 6 | + |
| 7 | +_not_implemented_message = "{} does not implement {}." |
| 8 | + |
| 9 | + |
| 10 | +class ExtensionArray(metaclass=abc.ABCMeta): |
| 11 | + """Abstract base class for custom array types |
| 12 | +
|
| 13 | + pandas will recognize instances of this class as proper arrays |
| 14 | + with a custom type and will not attempt to coerce them to objects. |
| 15 | +
|
| 16 | + Subclasses are expected to implement the following methods. |
| 17 | + """ |
| 18 | + # ------------------------------------------------------------------------ |
| 19 | + # Must be a Sequence |
| 20 | + # ------------------------------------------------------------------------ |
| 21 | + @abc.abstractmethod |
| 22 | + def __getitem__(self, item): |
| 23 | + pass |
| 24 | + |
| 25 | + def __setitem__(self, key, value): |
| 26 | + raise NotImplementedError(_not_implemented_message.format( |
| 27 | + type(self), '__setitem__') |
| 28 | + ) |
| 29 | + |
| 30 | + @abc.abstractmethod |
| 31 | + def __iter__(self): |
| 32 | + pass |
| 33 | + |
| 34 | + @abc.abstractmethod |
| 35 | + def __len__(self): |
| 36 | + pass |
| 37 | + |
| 38 | + # ------------------------------------------------------------------------ |
| 39 | + # Required attributes |
| 40 | + # ------------------------------------------------------------------------ |
| 41 | + @property |
| 42 | + @abc.abstractmethod |
| 43 | + def dtype(self): |
| 44 | + # type: () -> ExtensionDtype |
| 45 | + pass |
| 46 | + |
| 47 | + @property |
| 48 | + def shape(self): |
| 49 | + # type: () -> Tuple[int, ...] |
| 50 | + return (len(self),) |
| 51 | + |
| 52 | + @property |
| 53 | + def ndim(self): |
| 54 | + # type: () -> int |
| 55 | + """Extension Arrays are only allowed to be 1-dimensional""" |
| 56 | + return 1 |
| 57 | + |
| 58 | + @property |
| 59 | + @abc.abstractmethod |
| 60 | + def nbytes(self): |
| 61 | + # type: () -> int |
| 62 | + # TODO: default impl? |
| 63 | + pass |
| 64 | + |
| 65 | + # ------------------------------------------------------------------------ |
| 66 | + # Additional Methods |
| 67 | + # ------------------------------------------------------------------------ |
| 68 | + @abc.abstractmethod |
| 69 | + def isna(self): |
| 70 | + # type: () -> Sequence[bool] |
| 71 | + # TODO: narrow this type? |
| 72 | + pass |
| 73 | + |
| 74 | + # ------------------------------------------------------------------------ |
| 75 | + # Indexing methods |
| 76 | + # ------------------------------------------------------------------------ |
| 77 | + @abc.abstractmethod |
| 78 | + def take(self, indexer, allow_fill=True, fill_value=None): |
| 79 | + # type: (Sequence, bool, Optional[Any]) -> ExtensionArray |
| 80 | + """For slicing""" |
| 81 | + |
| 82 | + @abc.abstractmethod |
| 83 | + def take_nd(self, indexer, allow_fill=True, fill_value=None): |
| 84 | + """For slicing""" |
| 85 | + # TODO: this isn't nescesary if we only allow 1D (though maybe |
| 86 | + # impelment it). |
| 87 | + |
| 88 | + @abc.abstractmethod |
| 89 | + def copy(self, deep=False): |
| 90 | + # type: (bool) -> ExtensionArray |
| 91 | + """Return a copy of the array.""" |
| 92 | + |
| 93 | + # ------------------------------------------------------------------------ |
| 94 | + # Block-related methods |
| 95 | + # ------------------------------------------------------------------------ |
| 96 | + @property |
| 97 | + def _fill_value(self): |
| 98 | + """The missing value for this type, e.g. np.nan""" |
| 99 | + # type: () -> Any |
| 100 | + return None |
| 101 | + |
| 102 | + @abc.abstractmethod |
| 103 | + def _formatting_values(self): |
| 104 | + # type: () -> np.ndarray |
| 105 | + # At the moment, this has to be an array since we use result.dtype |
| 106 | + """An array of values to be printed in, e.g. the Series repr""" |
| 107 | + |
| 108 | + @classmethod |
| 109 | + @abc.abstractmethod |
| 110 | + def _concat_same_type(cls, to_concat): |
| 111 | + # type: (Sequence[ExtensionArray]) -> ExtensionArray |
| 112 | + """Concatenate multiple array |
| 113 | +
|
| 114 | + Parameters |
| 115 | + ---------- |
| 116 | + to_concat : sequence of this type |
| 117 | +
|
| 118 | + Returns |
| 119 | + ------- |
| 120 | + ExtensionArray |
| 121 | + """ |
| 122 | + |
| 123 | + @abc.abstractmethod |
| 124 | + def get_values(self): |
| 125 | + # type: () -> np.ndarray |
| 126 | + """Get the underlying values backing your data |
| 127 | + """ |
| 128 | + pass |
| 129 | + |
| 130 | + def _can_hold_na(self): |
| 131 | + """Whether your array can hold missing values. True by default. |
| 132 | +
|
| 133 | + Notes |
| 134 | + ----- |
| 135 | + Setting this to false will optimize some operations like fillna. |
| 136 | + """ |
| 137 | + # type: () -> bool |
| 138 | + return True |
| 139 | + |
| 140 | + @property |
| 141 | + def is_sparse(self): |
| 142 | + """Whether your array is sparse. True by default.""" |
| 143 | + # type: () -> bool |
| 144 | + return False |
| 145 | + |
| 146 | + @abc.abstractmethod |
| 147 | + def _slice(self, slicer): |
| 148 | + # type: (Union[tuple, Sequence, int]) -> 'ExtensionArray' |
| 149 | + """Return a new array sliced by `slicer`. |
| 150 | +
|
| 151 | + Parameters |
| 152 | + ---------- |
| 153 | + slicer : slice or np.ndarray |
| 154 | + If an array, it should just be a boolean mask |
| 155 | +
|
| 156 | + Returns |
| 157 | + ------- |
| 158 | + array : ExtensionArray |
| 159 | + Should return an ExtensionArray, even if ``self[slicer]`` |
| 160 | + would return a scalar. |
| 161 | + """ |
| 162 | + # XXX: We could get rid of this *if* we require that |
| 163 | + # ExtensionArray(extension_array[x]) always work. |
| 164 | + # That seems fine for when extension_array[x] is an ExtensionArray |
| 165 | + # but what if extension_array[x] reduces dimensionality? |
| 166 | + |
| 167 | + def value_counts(self, dropna=True): |
| 168 | + """Optional method for computing the histogram of the counts. |
| 169 | +
|
| 170 | + Parameters |
| 171 | + ---------- |
| 172 | + dropna : bool, default True |
| 173 | + whether to exclude missing values from the computation |
| 174 | +
|
| 175 | + Returns |
| 176 | + ------- |
| 177 | + counts : Series |
| 178 | + """ |
| 179 | + from pandas.core.algorithms import value_counts |
| 180 | + mask = ~np.asarray(self.isna()) |
| 181 | + values = self[mask] # XXX: this imposes boolean indexing |
| 182 | + return value_counts(np.asarray(values), dropna=dropna) |
0 commit comments