-
-
Notifications
You must be signed in to change notification settings - Fork 18.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
ENH: Allow storing ExtensionArrays in containers #19520
Changes from 99 commits
b7069ef
9cd92c7
9211bbd
80f83a6
ca004d8
5d4a686
9f4ad42
b1db4e8
00d6bb3
1608e3d
52e2180
e6d06e2
d356f19
a6ae340
41f09d8
29cfd7c
05eb9f3
82fd0c6
8b1e7d6
10af4b6
cd5f1eb
0a9d9fd
3185f4e
ffa888a
5a59591
476f75d
b15ee5a
659073f
b15ecac
88b8f4f
349ac1a
27ab045
8358fb1
8ef34a9
340d11b
8297888
7accb67
9b8d2a5
9fbac29
55305dc
0e63708
fbbbc8a
46a0a49
2c4445a
5612cda
b012c19
d49e6aa
d7d31ee
7b89f1b
b0dbffd
66b936f
32ee0ef
a9882e2
f53652a
2425621
fc337de
6abe9da
512fb89
c5db5da
0b112f2
170d0c7
402620f
b556f83
268aabc
d671259
cb740ed
d9e8dd6
815d202
a727b21
f368c29
d74c5c9
0ec6958
8104ee5
4d08218
f8e29b9
0cd9faa
8fcdb70
34a6a22
b4de5c4
c233c28
d6e8051
3af8a21
3a5118b
1e8e87e
0f5e4f0
1436d1d
c4dab88
a312ba5
758689f
02c3d40
9e17037
4599db4
d34d9ca
29d2528
905d72e
412c951
78834f1
f8eac55
f09c863
cedb63d
cae2c26
8088096
8aed325
453728a
cc13c8d
f90ac07
4a03b26
635223f
cf423a7
2d1a66c
c849865
c3ec822
f4cf45c
9c5d479
1175c0d
c816d99
9c9f59e
08af9a3
2e992f7
cc5cc3e
704ee67
c262968
8bf0334
c8d88da
24f3b60
50bd5dd
879bc84
33c9d1f
f07c166
79d43b1
91c629b
a1ebf53
aa57cad
c82748c
e919343
1ea74da
0c41a34
009bece
ea5562b
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -15,6 +15,7 @@ | |
is_unsigned_integer_dtype, is_signed_integer_dtype, | ||
is_integer_dtype, is_complex_dtype, | ||
is_object_dtype, | ||
is_extension_array_dtype, | ||
is_categorical_dtype, is_sparse, | ||
is_period_dtype, | ||
is_numeric_dtype, is_float_dtype, | ||
|
@@ -542,7 +543,7 @@ def value_counts(values, sort=True, ascending=False, normalize=False, | |
|
||
else: | ||
|
||
if is_categorical_dtype(values) or is_sparse(values): | ||
if is_extension_array_dtype(values) or is_sparse(values): | ||
|
||
# handle Categorical and sparse, | ||
result = Series(values).values.value_counts(dropna=dropna) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Shouldn't this be There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This should be
What types do you mean by others? Internally, our only type returning true here is Categorical (or sparse of is_sparse). There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yeah, forgot again for a moment that we don't yet have those other internal extension arrays apart from Categorical :) There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I also wonder why we're doing Probably better to make an |
||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -25,14 +25,14 @@ class ExtensionArray(object): | |
* isna | ||
* take | ||
* copy | ||
* _formatting_values | ||
* _concat_same_type | ||
|
||
Some additional methods are required to satisfy pandas' internal, private | ||
block API. | ||
|
||
* _concat_same_type | ||
* _can_hold_na | ||
* _formatting_values | ||
* _fill_value | ||
|
||
This class does not inherit from 'abc.ABCMeta' for performance reasons. | ||
Methods and properties required by the interface raise | ||
|
@@ -53,9 +53,6 @@ class ExtensionArray(object): | |
Extension arrays should be able to be constructed with instances of | ||
the class, i.e. ``ExtensionArray(extension_array)`` should return | ||
an instance, not error. | ||
|
||
Additionally, certain methods and interfaces are required for proper | ||
this array to be properly stored inside a ``DataFrame`` or ``Series``. | ||
""" | ||
# ------------------------------------------------------------------------ | ||
# Must be a Sequence | ||
|
@@ -92,7 +89,37 @@ def __getitem__(self, item): | |
raise AbstractMethodError(self) | ||
|
||
def __setitem__(self, key, value): | ||
# type: (Any, Any) -> None | ||
# type: (Union[int, np.ndarray], Any) -> None | ||
"""Set one or more values inplace. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Added some notes on the semantics of setitem if people want to take a look. |
||
|
||
Parameters | ||
---------- | ||
key : int or ndarray | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. this is incongruous with the below There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Added |
||
When called from, e.g. ``Series.__setitem__``, ``key`` will | ||
always be an ndarray of integers. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Is a boolean mask also converted to array of integers by pandas? If so, maybe explicitly mention that the developer can also implement boolean mask and slicing (to be similar to ndarray), but that this is not required for pandas? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Boolean setitem seems to be broken right now. Adding a test. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Should the the above sentence in the docstring be updated? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. could also be a slice |
||
value : ExtensionDtype.type, Sequence[ExtensionDtype.type], or object | ||
ExtensionArrays may | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. may ... (something missing?) |
||
|
||
Notes | ||
----- | ||
This method is not required to satisfy the interface. If an | ||
ExtensionArray chooses to implement __setitem__, then some semantics | ||
should be observed. | ||
|
||
* Setting multiple values : ExtensionArrays should support setting | ||
multiple values at once, ``key`` will be a sequence of integers. | ||
|
||
* Broadcasting : For a sequence ``key`` and a scalar ``value``, | ||
each position in ``key`` should be set to ``value``. | ||
|
||
* Coercion : Most users will expect basic coercion to work. For | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. this is very hard to support / do. I would not mention this, and its up to the EA subclass to do this (and to be honest kind of breaks the contract, IOW this is supposed to be an integer / slice and not a coercible) There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It's indeed up to the EA author to decide on this, but this is about coercing There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This section may not be appropriate for the docstring anyway. I'll remove it and add it to the narrative docs (which I've started on another branch). There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
To clarify, we have two consumers of the docs. Library authors implementing an EA and users of that library's EA. To the extent possible, I think we should write docstrings for users of the EA. We can put notes on expected implementation elsewhere. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Another possibility (or in addition) is to leave some implementation comments as actual comments. Like
as I think it is useful to keep some of those things in the code itself, for someone looking at the base class implementation. |
||
example, a string like ``'2018-01-01'`` is coerced to a datetime | ||
when setting on a datetime64ns array. In general, if the | ||
``__init__`` method coerces that value, then so should ``__setitem__``. | ||
|
||
When called from, e.g. ``Series.__setitem__``, ``key`` will always | ||
be an ndarray of positions. | ||
""" | ||
raise NotImplementedError(_not_implemented_message.format( | ||
type(self), '__setitem__') | ||
) | ||
|
@@ -107,6 +134,16 @@ def __len__(self): | |
# type: () -> int | ||
raise AbstractMethodError(self) | ||
|
||
def __iter__(self): | ||
"""Iterate over elements. | ||
|
||
This needs to be implemented so that pandas recognizes extension arrays | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. can be a better doc-string here |
||
as list-like. The default implementation makes successive calls to | ||
``__getitem__``, which may be slower than necessary. | ||
""" | ||
for i in range(len(self)): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. why are you not just raising AbstractMethodError? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. this is tied intimately with the boxing concept of scalars, but this should be decoupled from getitem (yes its a valid implementation, but you would never actually do it this way), rather you would iterate on some underlying value and box it, not index into and as a side effect use getitem to box. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
We don't know how the subclass is storing things though, so there's no There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. so my point is that you cannot implement a default here, make the sub-classes do it. yes it might repeat some code, but its much better there i think. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Yes, we can (see the code). You "don't want" it, that something different :) There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. And some context: If I remove There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think it still might be better raise here by default and force the subclass to implement this (even if this impl). It is SO important for subclasses to pay attention to this, it should just be required. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. You can't do much better than this implementation. |
||
yield self[i] | ||
|
||
# ------------------------------------------------------------------------ | ||
# Required attributes | ||
# ------------------------------------------------------------------------ | ||
|
@@ -167,6 +204,25 @@ def isna(self): | |
""" | ||
raise AbstractMethodError(self) | ||
|
||
def value_counts(self, dropna=True): | ||
"""Compute a histogram of the counts of non-null values. | ||
|
||
Parameters | ||
---------- | ||
dropna : bool, default True | ||
Don't include counts of NaN | ||
|
||
Returns | ||
------- | ||
value_counts : Series | ||
""" | ||
from pandas import value_counts | ||
|
||
if dropna: | ||
self = self[~self.isna()] | ||
|
||
return value_counts(np.array(self)) | ||
|
||
# ------------------------------------------------------------------------ | ||
# Indexing methods | ||
# ------------------------------------------------------------------------ | ||
|
@@ -198,9 +254,8 @@ def take(self, indexer, allow_fill=True, fill_value=None): | |
|
||
Examples | ||
-------- | ||
Suppose the extension array somehow backed by a NumPy structured array | ||
and that the underlying structured array is stored as ``self.data``. | ||
Then ``take`` may be written as | ||
Suppose the extension array is backed by a NumPy array stored as | ||
``self.data``. Then ``take`` may be written as | ||
|
||
.. code-block:: python | ||
|
||
|
@@ -209,6 +264,10 @@ def take(self, indexer, allow_fill=True, fill_value=None): | |
result = self.data.take(indexer) | ||
result[mask] = self._fill_value | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. hmm, is there a reason we don't define There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Originally there was a There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. ok that's fine. I think we do need / want a way to set this and a property is good, and |
||
return type(self)(result) | ||
|
||
See Also | ||
-------- | ||
numpy.take | ||
""" | ||
raise AbstractMethodError(self) | ||
|
||
|
@@ -240,7 +299,7 @@ def _formatting_values(self): | |
# type: () -> np.ndarray | ||
# At the moment, this has to be an array since we use result.dtype | ||
"""An array of values to be printed in, e.g. the Series repr""" | ||
raise AbstractMethodError(self) | ||
return np.array(self) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. NO, this should be implemented only by subclasses. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Why? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is a very sensible default IMO, subclasses can always override if needed |
||
|
||
@classmethod | ||
def _concat_same_type(cls, to_concat): | ||
|
@@ -257,6 +316,7 @@ def _concat_same_type(cls, to_concat): | |
""" | ||
raise AbstractMethodError(cls) | ||
|
||
@property | ||
def _can_hold_na(self): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Interface change: This should have been a property. |
||
# type: () -> bool | ||
"""Whether your array can hold missing values. True by default. | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -2141,6 +2141,10 @@ def repeat(self, repeats, *args, **kwargs): | |
def _can_hold_na(self): | ||
return True | ||
|
||
@property | ||
def _fill_value(self): | ||
return np.nan | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I general this fill_value would depend on the type of the categories ... There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yes... I'll fix that. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. should be:
|
||
|
||
@classmethod | ||
def _concat_same_type(self, to_concat): | ||
from pandas.core.dtypes.concat import _concat_categorical | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +1,6 @@ | ||
"""Extend pandas with custom array types""" | ||
import inspect | ||
|
||
from pandas.errors import AbstractMethodError | ||
|
||
|
||
|
@@ -106,7 +108,8 @@ def is_dtype(cls, dtype): | |
|
||
Parameters | ||
---------- | ||
dtype : str or dtype | ||
dtype : str, object, or type | ||
The dtype to check. | ||
|
||
Returns | ||
------- | ||
|
@@ -118,12 +121,15 @@ def is_dtype(cls, dtype): | |
|
||
1. ``cls.construct_from_string(dtype)`` is an instance | ||
of ``cls``. | ||
2. 'dtype' is ``cls`` or a subclass of ``cls``. | ||
2. ``dtype`` is an object and is an instance of ``cls`` | ||
3. 'dtype' is a class and is ``cls`` or a subclass of ``cls``. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. shouldn't this have double-ticks? |
||
""" | ||
if isinstance(dtype, str): | ||
try: | ||
return isinstance(cls.construct_from_string(dtype), cls) | ||
except TypeError: | ||
return False | ||
else: | ||
elif inspect.isclass(dtype): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. you have 2 conditions the same here There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
return issubclass(dtype, cls) | ||
else: | ||
return isinstance(dtype, cls) |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -10,9 +10,10 @@ | |
is_datetimelike_v_numeric, is_float_dtype, | ||
is_datetime64_dtype, is_datetime64tz_dtype, | ||
is_timedelta64_dtype, is_interval_dtype, | ||
is_complex_dtype, is_categorical_dtype, | ||
is_complex_dtype, | ||
is_string_like_dtype, is_bool_dtype, | ||
is_integer_dtype, is_dtype_equal, | ||
is_extension_array_dtype, | ||
needs_i8_conversion, _ensure_object, | ||
pandas_dtype, | ||
is_scalar, | ||
|
@@ -52,12 +53,15 @@ def isna(obj): | |
|
||
|
||
def _isna_new(obj): | ||
from ..arrays import ExtensionArray | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. pls don't do this. rather define an ABCExtensionArray. instead. This is the purpose of these, to avoid smell like this. |
||
|
||
if is_scalar(obj): | ||
return libmissing.checknull(obj) | ||
# hack (for now) because MI registers as ndarray | ||
elif isinstance(obj, ABCMultiIndex): | ||
raise NotImplementedError("isna is not defined for MultiIndex") | ||
elif isinstance(obj, (ABCSeries, np.ndarray, ABCIndexClass)): | ||
elif isinstance(obj, (ABCSeries, np.ndarray, ABCIndexClass, | ||
ExtensionArray)): | ||
return _isna_ndarraylike(obj) | ||
elif isinstance(obj, ABCGeneric): | ||
return obj._constructor(obj._data.isna(func=isna)) | ||
|
@@ -124,17 +128,18 @@ def _use_inf_as_na(key): | |
|
||
|
||
def _isna_ndarraylike(obj): | ||
|
||
values = getattr(obj, 'values', obj) | ||
dtype = values.dtype | ||
|
||
if is_string_dtype(dtype): | ||
if is_categorical_dtype(values): | ||
from pandas import Categorical | ||
if not isinstance(values, Categorical): | ||
values = values.values | ||
result = values.isna() | ||
elif is_interval_dtype(values): | ||
if is_extension_array_dtype(obj): | ||
if isinstance(obj, (ABCIndexClass, ABCSeries)): | ||
values = obj._values | ||
else: | ||
values = obj | ||
result = values.isna() | ||
elif is_string_dtype(dtype): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I know it was already there, but I find the use of
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. instead of this, pls fix is_string_dtype (to exclude interval as well as period dtypes (you might be able to say object and not extension_type). There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This will fix itself once IntervalArray is a proper extension type. Added tests to confirm that extension types are not True for |
||
if is_interval_dtype(values): | ||
# TODO(IntervalArray): remove this if block | ||
from pandas import IntervalIndex | ||
result = IntervalIndex(obj).isna() | ||
else: | ||
|
@@ -406,4 +411,7 @@ def remove_na_arraylike(arr): | |
""" | ||
Return array-like containing only true/non-NaN values, possibly empty. | ||
""" | ||
return arr[notna(lib.values_from_object(arr))] | ||
if is_extension_array_dtype(arr): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. ultimately values_from_object just calls .get_values() on the object if it exists. This smells like something is missing from the EA interface. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I don't think this if / elif can be avoided. |
||
return arr[notna(arr)] | ||
else: | ||
return arr[notna(lib.values_from_object(arr))] |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -39,6 +39,7 @@ | |
is_categorical_dtype, | ||
is_object_dtype, | ||
is_extension_type, | ||
is_extension_array_dtype, | ||
is_datetimetz, | ||
is_datetime64_any_dtype, | ||
is_datetime64tz_dtype, | ||
|
@@ -71,7 +72,7 @@ | |
create_block_manager_from_arrays, | ||
create_block_manager_from_blocks) | ||
from pandas.core.series import Series | ||
from pandas.core.arrays import Categorical | ||
from pandas.core.arrays import Categorical, ExtensionArray | ||
import pandas.core.algorithms as algorithms | ||
from pandas.compat import (range, map, zip, lrange, lmap, lzip, StringIO, u, | ||
OrderedDict, raise_with_traceback) | ||
|
@@ -511,7 +512,7 @@ def _get_axes(N, K, index=index, columns=columns): | |
index, columns = _get_axes(len(values), 1) | ||
return _arrays_to_mgr([values], columns, index, columns, | ||
dtype=dtype) | ||
elif is_datetimetz(values): | ||
elif (is_datetimetz(values) or is_extension_array_dtype(values)): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. What happens if the dtype is an extension dtype? (like the check above for categorical) Similar for Series, we need to either define what There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. In [7]: pd.Series([0, 1, 2], dtype=cyberpandas.IPType())
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-7-7fc01964da1d> in <module>()
----> 1 pd.Series([0, 1, 2], dtype=cyberpandas.IPType())
~/sandbox/pandas-ip/pandas/pandas/core/series.py in __init__(self, data, index, dtype, name, copy, fastpath)
246 else:
247 data = _sanitize_array(data, index, dtype, copy,
--> 248 raise_cast_failure=True)
249
250 data = SingleBlockManager(data, index, fastpath=True)
~/sandbox/pandas-ip/pandas/pandas/core/series.py in _sanitize_array(data, index, dtype, copy, raise_cast_failure)
3214 if dtype is not None:
3215 try:
-> 3216 subarr = _try_cast(data, False)
3217 except Exception:
3218 if raise_cast_failure: # pragma: no cover
~/sandbox/pandas-ip/pandas/pandas/core/series.py in _try_cast(arr, take_fast_path)
3168 subarr = maybe_cast_to_datetime(arr, dtype)
3169 if not is_extension_type(subarr):
-> 3170 subarr = np.array(subarr, dtype=dtype, copy=copy)
3171 except (ValueError, TypeError):
3172 if is_categorical_dtype(dtype):
TypeError: data type not understood How should we handle this? I'm fine with raising with a better error message. We don't know how to cast from Although... maybe we could support Oh hey, that "works" In [10]: pd.Series(cyberpandas.IPArray([0, 1, 2]), dtype=cyberpandas.IPType())
Out[10]:
0 0.0.0.0
1 0.0.0.1
2 0.0.0.2
dtype: ip But it only works since we ignore the dtype entirely :) I will raise if There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. also for things like There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. isn't a dateimetz an extension type now? why can't you remove the first part of the clauase? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Nope, not yet. Just |
||
# GH19157 | ||
if columns is None: | ||
columns = [0] | ||
|
@@ -2819,15 +2820,15 @@ def reindexer(value): | |
# now align rows | ||
value = reindexer(value).T | ||
|
||
elif isinstance(value, Categorical): | ||
elif isinstance(value, ExtensionArray): | ||
value = value.copy() | ||
|
||
elif isinstance(value, Index) or is_sequence(value): | ||
from pandas.core.series import _sanitize_index | ||
|
||
# turn me into an ndarray | ||
value = _sanitize_index(value, self.index, copy=False) | ||
if not isinstance(value, (np.ndarray, Index)): | ||
if not isinstance(value, (np.ndarray, Index, ExtensionArray)): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. you can use There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. ? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I'll rust remove this change until we support array-backed indexes. |
||
if isinstance(value, list) and len(value) > 0: | ||
value = maybe_convert_platform(value) | ||
else: | ||
|
@@ -2849,7 +2850,7 @@ def reindexer(value): | |
value = maybe_cast_to_datetime(value, value.dtype) | ||
|
||
# return internal types directly | ||
if is_extension_type(value): | ||
if is_extension_type(value) or is_extension_array_dtype(value): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is an unfortunate intermediate stage where some of our internal extension types (sparse, datetime w/ tz) are not yet actual extension array types. We'll be able to clean this up this eventually. |
||
return value | ||
|
||
# broadcast across multiple columns if necessary | ||
|
@@ -3386,12 +3387,8 @@ class max type | |
new_obj = self.copy() | ||
|
||
def _maybe_casted_values(index, labels=None): | ||
if isinstance(index, PeriodIndex): | ||
values = index.astype(object).values | ||
elif isinstance(index, DatetimeIndex) and index.tz is not None: | ||
values = index | ||
else: | ||
values = index.values | ||
values = index._values | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Can you put a small comment here what the intent of the function is? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. hmm I'm not really sure :) It also seems to just be used in one place, so this seems like an opportunity for cleanup. This change is possible because |
||
if not isinstance(index, (PeriodIndex, DatetimeIndex)): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. what are you trying to do here? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is identical to what happened before in the |
||
if values.dtype == np.object_: | ||
values = lib.maybe_convert_objects(values) | ||
|
||
|
@@ -5640,7 +5637,7 @@ def count(self, axis=0, level=None, numeric_only=False): | |
if len(frame._get_axis(axis)) == 0: | ||
result = Series(0, index=frame._get_agg_axis(axis)) | ||
else: | ||
if frame._is_mixed_type: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. this whole count things should be cleaned up anyhow, can you add an issue about this, this optimization is not worth it an makes code more complex (not about your changes, but the mixed type stuff) |
||
if frame._is_mixed_type or frame._data.any_extension_types: | ||
result = notna(frame).sum(axis=axis) | ||
else: | ||
counts = notna(frame.values).sum(axis=axis) | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -13,6 +13,7 @@ | |
from pandas import compat | ||
|
||
from pandas.core.accessor import CachedAccessor | ||
from pandas.core.arrays import ExtensionArray | ||
from pandas.core.dtypes.generic import ( | ||
ABCSeries, ABCDataFrame, | ||
ABCMultiIndex, | ||
|
@@ -2002,6 +2003,7 @@ def _format_with_header(self, header, na_rep='NaN', **kwargs): | |
|
||
if is_categorical_dtype(values.dtype): | ||
values = np.array(values) | ||
|
||
elif is_object_dtype(values.dtype): | ||
values = lib.maybe_convert_objects(values, safe=1) | ||
|
||
|
@@ -2601,7 +2603,7 @@ def get_value(self, series, key): | |
# if we have something that is Index-like, then | ||
# use this, e.g. DatetimeIndex | ||
s = getattr(series, '_values', None) | ||
if isinstance(s, Index) and is_scalar(key): | ||
if isinstance(s, (ExtensionArray, Index)) and is_scalar(key): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. is_array_like might work here |
||
try: | ||
return s[key] | ||
except (IndexError, ValueError): | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
is_sparse should be recognized as an extension array type
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It's on my todo list. I'll do it after interval.