diff --git a/doc/source/extending.rst b/doc/source/extending.rst index 38b3b19031a0e..dcabfed2b6021 100644 --- a/doc/source/extending.rst +++ b/doc/source/extending.rst @@ -91,8 +91,16 @@ extension array for IP Address data, this might be ``ipaddress.IPv4Address``. See the `extension dtype source`_ for interface definition. +.. versionadded:: 0.24.0 + +:class:`pandas.api.extension.ExtensionDtype` can be registered to pandas to allow creation via a string dtype name. +This allows one to instantiate ``Series`` and ``.astype()`` with a registered string name, for +example ``'category'`` is a registered string accessor for the ``CategoricalDtype``. + +See the `extension dtype dtypes`_ for more on how to register dtypes. + :class:`~pandas.api.extensions.ExtensionArray` -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ This class provides all the array-like functionality. ExtensionArrays are limited to 1 dimension. An ExtensionArray is linked to an ExtensionDtype via the @@ -179,6 +187,7 @@ To use a test, subclass it: See https://github.com/pandas-dev/pandas/blob/master/pandas/tests/extension/base/__init__.py for a list of all the tests available. +.. _extension dtype dtypes: https://github.com/pandas-dev/pandas/blob/master/pandas/core/dtypes/dtypes.py .. _extension dtype source: https://github.com/pandas-dev/pandas/blob/master/pandas/core/dtypes/base.py .. _extension array source: https://github.com/pandas-dev/pandas/blob/master/pandas/core/arrays/base.py diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index dfb7a3675fdd5..f3aea74c88e48 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -128,6 +128,23 @@ Previous Behavior: In [3]: pi - pi[0] Out[3]: Int64Index([0, 1, 2], dtype='int64') +.. _whatsnew_0240.api.extension: + +ExtensionType Changes +^^^^^^^^^^^^^^^^^^^^^ + +- ``ExtensionDtype`` has gained the ability to instantiate from string dtypes, e.g. ``decimal`` would instantiate a registered ``DecimalDtype``; furthermore + the ``ExtensionDtype`` has gained the method ``construct_array_type`` (:issue:`21185`) +- The ``ExtensionArray`` constructor, ``_from_sequence`` now take the keyword arg ``copy=False`` (:issue:`21185`) +- Bug in :meth:`Series.get` for ``Series`` using ``ExtensionArray`` and integer index (:issue:`21257`) +- :meth:`Series.combine()` works correctly with :class:`~pandas.api.extensions.ExtensionArray` inside of :class:`Series` (:issue:`20825`) +- :meth:`Series.combine()` with scalar argument now works for any function type (:issue:`21248`) +- + +.. _whatsnew_0240.api.other: + +Other API Changes +^^^^^^^^^^^^^^^^^ .. _whatsnew_0240.api.incompatibilities: @@ -168,6 +185,7 @@ Other API Changes ^^^^^^^^^^^^^^^^^ - :class:`DatetimeIndex` now accepts :class:`Int64Index` arguments as epoch timestamps (:issue:`20997`) +- Invalid construction of ``IntervalDtype`` will now always raise a ``TypeError`` rather than a ``ValueError`` if the subdtype is invalid (:issue:`21185`) - - @@ -344,13 +362,6 @@ Reshaping - - -ExtensionArray -^^^^^^^^^^^^^^ - -- Bug in :meth:`Series.get` for ``Series`` using ``ExtensionArray`` and integer index (:issue:`21257`) -- :meth:`Series.combine()` works correctly with :class:`~pandas.api.extensions.ExtensionArray` inside of :class:`Series` (:issue:`20825`) -- :meth:`Series.combine()` with scalar argument now works for any function type (:issue:`21248`) -- - Other diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index dc726a736d34f..c4e4f5471c4be 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -154,7 +154,7 @@ def _reconstruct_data(values, dtype, original): """ from pandas import Index if is_extension_array_dtype(dtype): - pass + values = dtype.construct_array_type()._from_sequence(values) elif is_datetime64tz_dtype(dtype) or is_period_dtype(dtype): values = Index(original)._shallow_copy(values, name=None) elif is_bool_dtype(dtype): @@ -705,7 +705,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) diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py index a572fff1c44d7..fe4e461b0bd4f 100644 --- a/pandas/core/arrays/base.py +++ b/pandas/core/arrays/base.py @@ -54,6 +54,7 @@ class ExtensionArray(object): methods: * fillna + * dropna * unique * factorize / _values_for_factorize * argsort / _values_for_argsort @@ -87,7 +88,7 @@ class ExtensionArray(object): # Constructors # ------------------------------------------------------------------------ @classmethod - def _from_sequence(cls, scalars): + def _from_sequence(cls, scalars, copy=False): """Construct a new ExtensionArray from a sequence of scalars. Parameters @@ -95,6 +96,8 @@ def _from_sequence(cls, scalars): scalars : Sequence Each element will be an instance of the scalar type for this array, ``cls.dtype.type``. + copy : boolean, default False + if True, copy the underlying data Returns ------- ExtensionArray @@ -384,6 +387,16 @@ def fillna(self, value=None, method=None, limit=None): new_values = self.copy() return new_values + def dropna(self): + """ Return ExtensionArray without NA values + + Returns + ------- + valid : ExtensionArray + """ + + return self[~self.isna()] + def unique(self): """Compute the ExtensionArray of unique values. diff --git a/pandas/core/dtypes/base.py b/pandas/core/dtypes/base.py index 49e98c16c716e..5f405e0d10657 100644 --- a/pandas/core/dtypes/base.py +++ b/pandas/core/dtypes/base.py @@ -109,6 +109,11 @@ class ExtensionDtype(_DtypeOpsMixin): * name * construct_from_string + Optionally one can override construct_array_type for construction + with the name of this dtype via the Registry + + * construct_array_type + The `na_value` class attribute can be used to set the default NA value for this type. :attr:`numpy.nan` is used by default. @@ -156,6 +161,16 @@ def name(self): """ raise AbstractMethodError(self) + @classmethod + def construct_array_type(cls): + """Return the array type associated with this dtype + + Returns + ------- + type + """ + raise NotImplementedError + @classmethod def construct_from_string(cls, string): """Attempt to construct this type from a string. diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index 65328dfc7347e..2cd8144e43cea 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -648,6 +648,11 @@ def conv(r, dtype): def astype_nansafe(arr, dtype, copy=True): """ return a view if copy is False, but need to be very careful as the result shape could change! """ + + # dispatch on extension dtype if needed + if is_extension_array_dtype(dtype): + return dtype.array_type._from_sequence(arr, copy=copy) + if not isinstance(dtype, np.dtype): dtype = pandas_dtype(dtype) diff --git a/pandas/core/dtypes/common.py b/pandas/core/dtypes/common.py index 05f82c67ddb8b..ef4f36dc6df33 100644 --- a/pandas/core/dtypes/common.py +++ b/pandas/core/dtypes/common.py @@ -5,10 +5,11 @@ PY3, PY36) from pandas._libs import algos, lib from pandas._libs.tslibs import conversion + from pandas.core.dtypes.dtypes import ( - CategoricalDtype, CategoricalDtypeType, DatetimeTZDtype, + registry, CategoricalDtype, CategoricalDtypeType, DatetimeTZDtype, DatetimeTZDtypeType, PeriodDtype, PeriodDtypeType, IntervalDtype, - IntervalDtypeType, ExtensionDtype, PandasExtensionDtype) + IntervalDtypeType, ExtensionDtype) from pandas.core.dtypes.generic import ( ABCCategorical, ABCPeriodIndex, ABCDatetimeIndex, ABCSeries, ABCSparseArray, ABCSparseSeries, ABCCategoricalIndex, ABCIndexClass, @@ -1977,38 +1978,13 @@ def pandas_dtype(dtype): np.dtype or a pandas dtype """ - if isinstance(dtype, DatetimeTZDtype): - return dtype - elif isinstance(dtype, PeriodDtype): - return dtype - elif isinstance(dtype, CategoricalDtype): - return dtype - elif isinstance(dtype, IntervalDtype): - return dtype - elif isinstance(dtype, string_types): - try: - return DatetimeTZDtype.construct_from_string(dtype) - except TypeError: - pass - - if dtype.startswith('period[') or dtype.startswith('Period['): - # do not parse string like U as period[U] - try: - return PeriodDtype.construct_from_string(dtype) - except TypeError: - pass - - elif dtype.startswith('interval') or dtype.startswith('Interval'): - try: - return IntervalDtype.construct_from_string(dtype) - except TypeError: - pass + # registered extension types + result = registry.find(dtype) + if result is not None: + return result - try: - return CategoricalDtype.construct_from_string(dtype) - except TypeError: - pass - elif isinstance(dtype, (PandasExtensionDtype, ExtensionDtype)): + # un-registered extension types + if isinstance(dtype, ExtensionDtype): return dtype try: diff --git a/pandas/core/dtypes/dtypes.py b/pandas/core/dtypes/dtypes.py index 1e762c2be92a6..de837efc235a0 100644 --- a/pandas/core/dtypes/dtypes.py +++ b/pandas/core/dtypes/dtypes.py @@ -8,6 +8,65 @@ from .base import ExtensionDtype, _DtypeOpsMixin +class Registry(object): + """ + Registry for dtype inference + + The registry allows one to map a string repr of a extension + dtype to an extenstion dtype. + + Multiple extension types can be registered. + These are tried in order. + + Examples + -------- + registry.register(MyExtensionDtype) + """ + dtypes = [] + + @classmethod + def register(self, dtype): + """ + Parameters + ---------- + dtype : ExtensionDtype + """ + if not issubclass(dtype, (PandasExtensionDtype, ExtensionDtype)): + raise ValueError("can only register pandas extension dtypes") + + self.dtypes.append(dtype) + + def find(self, dtype): + """ + Parameters + ---------- + dtype : PandasExtensionDtype or string + + Returns + ------- + return the first matching dtype, otherwise return None + """ + if not isinstance(dtype, compat.string_types): + dtype_type = dtype + if not isinstance(dtype, type): + dtype_type = type(dtype) + if issubclass(dtype_type, (PandasExtensionDtype, ExtensionDtype)): + return dtype + + return None + + for dtype_type in self.dtypes: + try: + return dtype_type.construct_from_string(dtype) + except TypeError: + pass + + return None + + +registry = Registry() + + class PandasExtensionDtype(_DtypeOpsMixin): """ A np.dtype duck-typed class, suitable for holding a custom dtype. @@ -265,6 +324,17 @@ def _hash_categories(categories, ordered=True): else: return np.bitwise_xor.reduce(hashed) + @classmethod + def construct_array_type(cls): + """Return the array type associated with this dtype + + Returns + ------- + type + """ + from pandas import Categorical + return Categorical + @classmethod def construct_from_string(cls, string): """ attempt to construct this type from a string, raise a TypeError if @@ -556,11 +626,16 @@ def _parse_dtype_strict(cls, freq): @classmethod def construct_from_string(cls, string): """ - attempt to construct this type from a string, raise a TypeError - if its not possible + Strict construction from a string, raise a TypeError if not + possible """ from pandas.tseries.offsets import DateOffset - if isinstance(string, (compat.string_types, DateOffset)): + + if (isinstance(string, compat.string_types) and + (string.startswith('period[') or + string.startswith('Period[')) or + isinstance(string, DateOffset)): + # do not parse string like U as period[U] # avoid tuple to be regarded as freq try: return cls(freq=string) @@ -660,7 +735,7 @@ def __new__(cls, subtype=None): try: subtype = pandas_dtype(subtype) except TypeError: - raise ValueError("could not construct IntervalDtype") + raise TypeError("could not construct IntervalDtype") if is_categorical_dtype(subtype) or is_string_dtype(subtype): # GH 19016 @@ -682,8 +757,11 @@ def construct_from_string(cls, string): attempt to construct this type from a string, raise a TypeError if its not possible """ - if isinstance(string, compat.string_types): + if (isinstance(string, compat.string_types) and + (string.startswith('interval') or + string.startswith('Interval'))): return cls(string) + msg = "a string needs to be passed, got type {typ}" raise TypeError(msg.format(typ=type(string))) @@ -727,3 +805,10 @@ def is_dtype(cls, dtype): else: return False return super(IntervalDtype, cls).is_dtype(dtype) + + +# register the dtypes in search order +registry.register(DatetimeTZDtype) +registry.register(PeriodDtype) +registry.register(IntervalDtype) +registry.register(CategoricalDtype) diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py index 80619c7beb28c..2fd4e099777bf 100644 --- a/pandas/core/indexes/interval.py +++ b/pandas/core/indexes/interval.py @@ -796,7 +796,7 @@ def astype(self, dtype, copy=True): @cache_readonly def dtype(self): """Return the dtype object of the underlying data""" - return IntervalDtype.construct_from_string(str(self.left.dtype)) + return IntervalDtype(self.left.dtype.name) @property def inferred_type(self): diff --git a/pandas/core/internals.py b/pandas/core/internals.py index e44c0f1b8e69d..e42953d618659 100644 --- a/pandas/core/internals.py +++ b/pandas/core/internals.py @@ -633,8 +633,9 @@ def _astype(self, dtype, copy=False, errors='raise', values=None, return self.make_block(Categorical(self.values, dtype=dtype)) # astype processing - dtype = np.dtype(dtype) - if self.dtype == dtype: + if not is_extension_array_dtype(dtype): + dtype = np.dtype(dtype) + if is_dtype_equal(self.dtype, dtype): if copy: return self.copy() return self @@ -662,7 +663,13 @@ def _astype(self, dtype, copy=False, errors='raise', values=None, # _astype_nansafe works fine with 1-d only values = astype_nansafe(values.ravel(), dtype, copy=True) - values = values.reshape(self.shape) + + # TODO(extension) + # should we make this attribute? + try: + values = values.reshape(self.shape) + except AttributeError: + pass newb = make_block(values, placement=self.mgr_locs, klass=klass) @@ -3172,6 +3179,10 @@ def get_block_type(values, dtype=None): cls = TimeDeltaBlock elif issubclass(vtype, np.complexfloating): cls = ComplexBlock + elif is_categorical(values): + cls = CategoricalBlock + elif is_extension_array_dtype(values): + cls = ExtensionBlock elif issubclass(vtype, np.datetime64): assert not is_datetimetz(values) cls = DatetimeBlock @@ -3181,10 +3192,6 @@ def get_block_type(values, dtype=None): cls = IntBlock elif dtype == np.bool_: cls = BoolBlock - elif is_categorical(values): - cls = CategoricalBlock - elif is_extension_array_dtype(values): - cls = ExtensionBlock else: cls = ObjectBlock return cls diff --git a/pandas/core/series.py b/pandas/core/series.py index eb333d6b451ee..93c1f866cad17 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -4094,11 +4094,9 @@ def _try_cast(arr, take_fast_path): subarr = Categorical(arr, dtype.categories, ordered=dtype.ordered) elif is_extension_array_dtype(dtype): - # We don't allow casting to third party dtypes, since we don't - # know what array belongs to which type. - msg = ("Cannot cast data to extension dtype '{}'. " - "Pass the extension array directly.".format(dtype)) - raise ValueError(msg) + # create an extension array from its dtype + array_type = dtype.construct_array_type() + subarr = array_type(subarr, copy=copy) elif dtype is not None and raise_cast_failure: raise diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py index c46f4b5ad9c18..2133d0c981b71 100644 --- a/pandas/io/formats/format.py +++ b/pandas/io/formats/format.py @@ -514,7 +514,6 @@ def _to_str_columns(self): Render a DataFrame to a list of columns (as lists of strings). """ frame = self.tr_frame - # may include levels names also str_index = self._get_formatted_index(frame) diff --git a/pandas/tests/dtypes/test_dtypes.py b/pandas/tests/dtypes/test_dtypes.py index eee53a2fcac6a..62e0f1cb717f0 100644 --- a/pandas/tests/dtypes/test_dtypes.py +++ b/pandas/tests/dtypes/test_dtypes.py @@ -7,10 +7,9 @@ from pandas import ( Series, Categorical, CategoricalIndex, IntervalIndex, date_range) -from pandas.compat import string_types from pandas.core.dtypes.dtypes import ( DatetimeTZDtype, PeriodDtype, - IntervalDtype, CategoricalDtype) + IntervalDtype, CategoricalDtype, registry) from pandas.core.dtypes.common import ( is_categorical_dtype, is_categorical, is_datetime64tz_dtype, is_datetimetz, @@ -448,7 +447,7 @@ def test_construction_not_supported(self, subtype): def test_construction_errors(self): msg = 'could not construct IntervalDtype' - with tm.assert_raises_regex(ValueError, msg): + with tm.assert_raises_regex(TypeError, msg): IntervalDtype('xx') def test_construction_from_string(self): @@ -458,14 +457,21 @@ def test_construction_from_string(self): assert is_dtype_equal(self.dtype, result) @pytest.mark.parametrize('string', [ - 'foo', 'interval[foo]', 'foo[int64]', 0, 3.14, ('a', 'b'), None]) + 'foo', 'foo[int64]', 0, 3.14, ('a', 'b'), None]) def test_construction_from_string_errors(self, string): - if isinstance(string, string_types): - error, msg = ValueError, 'could not construct IntervalDtype' - else: - error, msg = TypeError, 'a string needs to be passed, got type' + # these are invalid entirely + msg = 'a string needs to be passed, got type' + + with tm.assert_raises_regex(TypeError, msg): + IntervalDtype.construct_from_string(string) + + @pytest.mark.parametrize('string', [ + 'interval[foo]']) + def test_construction_from_string_error_subtype(self, string): + # this is an invalid subtype + msg = 'could not construct IntervalDtype' - with tm.assert_raises_regex(error, msg): + with tm.assert_raises_regex(TypeError, msg): IntervalDtype.construct_from_string(string) def test_subclass(self): @@ -767,3 +773,25 @@ def test_update_dtype_errors(self, bad_dtype): msg = 'a CategoricalDtype must be passed to perform an update, ' with tm.assert_raises_regex(ValueError, msg): dtype.update_dtype(bad_dtype) + + +@pytest.mark.parametrize( + 'dtype', + [DatetimeTZDtype, CategoricalDtype, + PeriodDtype, IntervalDtype]) +def test_registry(dtype): + assert dtype in registry.dtypes + + +@pytest.mark.parametrize( + 'dtype, expected', + [('int64', None), + ('interval', IntervalDtype()), + ('interval[int64]', IntervalDtype()), + ('interval[datetime64[ns]]', IntervalDtype('datetime64[ns]')), + ('category', CategoricalDtype()), + ('period[D]', PeriodDtype('D')), + ('datetime64[ns, US/Eastern]', DatetimeTZDtype('ns', 'US/Eastern'))]) +def test_registry_find(dtype, expected): + + assert registry.find(dtype) == expected diff --git a/pandas/tests/extension/base/constructors.py b/pandas/tests/extension/base/constructors.py index 489a430bb4020..fdd2b99d9b3c7 100644 --- a/pandas/tests/extension/base/constructors.py +++ b/pandas/tests/extension/base/constructors.py @@ -45,3 +45,14 @@ def test_series_given_mismatched_index_raises(self, data): msg = 'Length of passed values is 3, index implies 5' with tm.assert_raises_regex(ValueError, msg): pd.Series(data[:3], index=[0, 1, 2, 3, 4]) + + def test_from_dtype(self, data): + # construct from our dtype & string dtype + dtype = data.dtype + + expected = pd.Series(data) + result = pd.Series(list(data), dtype=dtype) + self.assert_series_equal(result, expected) + + result = pd.Series(list(data), dtype=str(dtype)) + self.assert_series_equal(result, expected) diff --git a/pandas/tests/extension/base/dtype.py b/pandas/tests/extension/base/dtype.py index 63d3d807c270c..52a12816c8722 100644 --- a/pandas/tests/extension/base/dtype.py +++ b/pandas/tests/extension/base/dtype.py @@ -1,3 +1,4 @@ +import pytest import numpy as np import pandas as pd @@ -46,3 +47,10 @@ def test_eq_with_str(self, dtype): def test_eq_with_numpy_object(self, dtype): assert dtype != np.dtype('object') + + def test_array_type(self, data, dtype): + assert dtype.construct_array_type() is type(data) + + def test_array_type_with_arg(self, data, dtype): + with pytest.raises(NotImplementedError): + dtype.construct_array_type('foo') diff --git a/pandas/tests/extension/base/interface.py b/pandas/tests/extension/base/interface.py index 8ef8debbdc666..69de0e1900831 100644 --- a/pandas/tests/extension/base/interface.py +++ b/pandas/tests/extension/base/interface.py @@ -40,6 +40,16 @@ def test_repr(self, data): df = pd.DataFrame({"A": data}) repr(df) + def test_repr_array(self, data): + # some arrays may be able to assert + # attributes in the repr + repr(data) + + def test_repr_array_long(self, data): + # some arrays may be able to assert a ... in the repr + with pd.option_context('display.max_seq_items', 1): + repr(data) + def test_dtype_name_in_info(self, data): buf = StringIO() pd.DataFrame({"A": data}).info(buf=buf) diff --git a/pandas/tests/extension/base/methods.py b/pandas/tests/extension/base/methods.py index 23227867ee4d7..c660687f16590 100644 --- a/pandas/tests/extension/base/methods.py +++ b/pandas/tests/extension/base/methods.py @@ -19,7 +19,8 @@ def test_value_counts(self, all_data, dropna): other = all_data result = pd.Series(all_data).value_counts(dropna=dropna).sort_index() - expected = pd.Series(other).value_counts(dropna=dropna).sort_index() + expected = pd.Series(other).value_counts( + dropna=dropna).sort_index() self.assert_series_equal(result, expected) diff --git a/pandas/tests/extension/base/missing.py b/pandas/tests/extension/base/missing.py index af26d83df3fe2..43b2702c72193 100644 --- a/pandas/tests/extension/base/missing.py +++ b/pandas/tests/extension/base/missing.py @@ -23,6 +23,11 @@ def test_isna(self, data_missing): expected = pd.Series([], dtype=bool) self.assert_series_equal(result, expected) + def test_dropna_array(self, data_missing): + result = data_missing.dropna() + expected = data_missing[[1]] + self.assert_extension_array_equal(result, expected) + def test_dropna_series(self, data_missing): ser = pd.Series(data_missing) result = ser.dropna() diff --git a/pandas/tests/extension/base/reshaping.py b/pandas/tests/extension/base/reshaping.py index fe920a47ab740..c83726c5278a5 100644 --- a/pandas/tests/extension/base/reshaping.py +++ b/pandas/tests/extension/base/reshaping.py @@ -84,6 +84,7 @@ def test_concat_columns(self, data, na_value): expected = pd.DataFrame({ 'A': data._from_sequence(list(data[:3]) + [na_value]), 'B': [np.nan, 1, 2, 3]}) + result = pd.concat([df1, df2], axis=1) self.assert_frame_equal(result, expected) result = pd.concat([df1['A'], df2['B']], axis=1) diff --git a/pandas/tests/extension/category/test_categorical.py b/pandas/tests/extension/category/test_categorical.py index ae0d72c204d13..715e8bd40a2d0 100644 --- a/pandas/tests/extension/category/test_categorical.py +++ b/pandas/tests/extension/category/test_categorical.py @@ -62,7 +62,9 @@ def data_for_grouping(): class TestDtype(base.BaseDtypeTests): - pass + + def test_array_type_with_arg(self, data, dtype): + assert dtype.construct_array_type() is Categorical class TestInterface(base.BaseInterfaceTests): diff --git a/pandas/tests/extension/decimal/array.py b/pandas/tests/extension/decimal/array.py index 3f2f24cd26af0..33adebbbe5780 100644 --- a/pandas/tests/extension/decimal/array.py +++ b/pandas/tests/extension/decimal/array.py @@ -16,6 +16,16 @@ class DecimalDtype(ExtensionDtype): name = 'decimal' na_value = decimal.Decimal('NaN') + @classmethod + def construct_array_type(cls): + """Return the array type associated with this dtype + + Returns + ------- + type + """ + return DecimalArray + @classmethod def construct_from_string(cls, string): if string == cls.name: @@ -28,7 +38,7 @@ def construct_from_string(cls, string): class DecimalArray(ExtensionArray, ExtensionScalarOpsMixin): dtype = DecimalDtype() - def __init__(self, values): + def __init__(self, values, copy=False): for val in values: if not isinstance(val, self.dtype.type): raise TypeError("All values must be of type " + @@ -44,7 +54,7 @@ def __init__(self, values): # self._values = self.values = self.data @classmethod - def _from_sequence(cls, scalars): + def _from_sequence(cls, scalars, copy=False): return cls(scalars) @classmethod diff --git a/pandas/tests/extension/decimal/test_decimal.py b/pandas/tests/extension/decimal/test_decimal.py index 45ee7f227c4f0..8fd3d1a57f6c8 100644 --- a/pandas/tests/extension/decimal/test_decimal.py +++ b/pandas/tests/extension/decimal/test_decimal.py @@ -100,7 +100,9 @@ def assert_frame_equal(self, left, right, *args, **kwargs): class TestDtype(BaseDecimal, base.BaseDtypeTests): - pass + + def test_array_type_with_arg(self, data, dtype): + assert dtype.construct_array_type() is DecimalArray class TestInterface(BaseDecimal, base.BaseInterfaceTests): @@ -108,7 +110,11 @@ class TestInterface(BaseDecimal, base.BaseInterfaceTests): class TestConstructors(BaseDecimal, base.BaseConstructorsTests): - pass + + @pytest.mark.xfail(reason="not implemented constructor from dtype") + def test_from_dtype(self, data): + # construct from our dtype & string dtype + pass class TestReshaping(BaseDecimal, base.BaseReshapingTests): @@ -155,6 +161,10 @@ class TestGroupby(BaseDecimal, base.BaseGroupbyTests): pass +# TODO(extension) +@pytest.mark.xfail(reason=( + "raising AssertionError as this is not implemented, " + "though easy enough to do")) def test_series_constructor_coerce_data_to_extension_dtype_raises(): xpr = ("Cannot cast data to extension dtype 'decimal'. Pass the " "extension array directly.") diff --git a/pandas/tests/extension/json/array.py b/pandas/tests/extension/json/array.py index d3043bf0852d2..160bf259e1e32 100644 --- a/pandas/tests/extension/json/array.py +++ b/pandas/tests/extension/json/array.py @@ -32,6 +32,16 @@ class JSONDtype(ExtensionDtype): # source compatibility with Py2. na_value = {} + @classmethod + def construct_array_type(cls): + """Return the array type associated with this dtype + + Returns + ------- + type + """ + return JSONArray + @classmethod def construct_from_string(cls, string): if string == cls.name: @@ -44,7 +54,7 @@ def construct_from_string(cls, string): class JSONArray(ExtensionArray): dtype = JSONDtype() - def __init__(self, values): + def __init__(self, values, copy=False): for val in values: if not isinstance(val, self.dtype.type): raise TypeError("All values must be of type " + @@ -59,7 +69,7 @@ def __init__(self, values): # self._values = self.values = self.data @classmethod - def _from_sequence(cls, scalars): + def _from_sequence(cls, scalars, copy=False): return cls(scalars) @classmethod diff --git a/pandas/tests/extension/json/test_json.py b/pandas/tests/extension/json/test_json.py index 268134dc8c333..7eeaf7946663e 100644 --- a/pandas/tests/extension/json/test_json.py +++ b/pandas/tests/extension/json/test_json.py @@ -107,7 +107,9 @@ def assert_frame_equal(self, left, right, *args, **kwargs): class TestDtype(BaseJSON, base.BaseDtypeTests): - pass + + def test_array_type_with_arg(self, data, dtype): + assert dtype.construct_array_type() is JSONArray class TestInterface(BaseJSON, base.BaseInterfaceTests): @@ -130,7 +132,11 @@ def test_custom_asserts(self): class TestConstructors(BaseJSON, base.BaseConstructorsTests): - pass + + @pytest.mark.xfail(reason="not implemented constructor from dtype") + def test_from_dtype(self, data): + # construct from our dtype & string dtype + pass class TestReshaping(BaseJSON, base.BaseReshapingTests):