From e0f6c2281bf803889d4ac6c7f8bdfd721715665b Mon Sep 17 00:00:00 2001 From: Jeremy Schendel Date: Fri, 25 May 2018 01:09:54 -0600 Subject: [PATCH 1/4] CLN: Remove duplicate Categorical section from 0.23.1 whatsnew (#21197) --- doc/source/whatsnew/v0.23.1.txt | 5 ----- 1 file changed, 5 deletions(-) diff --git a/doc/source/whatsnew/v0.23.1.txt b/doc/source/whatsnew/v0.23.1.txt index a7ba0dfbbd1c4..4876678baaa6e 100644 --- a/doc/source/whatsnew/v0.23.1.txt +++ b/doc/source/whatsnew/v0.23.1.txt @@ -97,8 +97,3 @@ Reshaping - Bug in :func:`concat` where error was raised in concatenating :class:`Series` with numpy scalar and tuple names (:issue:`21015`) - - -Categorical -^^^^^^^^^^^ - -- From dc02831f7b267ef152c9bb6a1c8e39c652c1ac3c Mon Sep 17 00:00:00 2001 From: Jeff Reback Date: Fri, 25 May 2018 07:32:05 -0400 Subject: [PATCH 2/4] CI: use latest deps for pandas-datareader, python-dateutil (#21204) --- ci/travis-36.yaml | 4 ++-- pandas/tests/test_downstream.py | 2 ++ 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/ci/travis-36.yaml b/ci/travis-36.yaml index fe057e714761e..006276ba1a65f 100644 --- a/ci/travis-36.yaml +++ b/ci/travis-36.yaml @@ -18,12 +18,10 @@ dependencies: - numexpr - numpy - openpyxl - - pandas-datareader - psycopg2 - pyarrow - pymysql - pytables - - python-dateutil - python-snappy - python=3.6* - pytz @@ -45,3 +43,5 @@ dependencies: - pip: - brotlipy - coverage + - pandas-datareader + - python-dateutil diff --git a/pandas/tests/test_downstream.py b/pandas/tests/test_downstream.py index a595d9f18d6b8..c28e2052bd93e 100644 --- a/pandas/tests/test_downstream.py +++ b/pandas/tests/test_downstream.py @@ -87,6 +87,7 @@ def test_pandas_gbq(df): pandas_gbq = import_module('pandas_gbq') # noqa +@pytest.mark.xfail(reason="0.7.0 pending") @tm.network def test_pandas_datareader(): @@ -95,6 +96,7 @@ def test_pandas_datareader(): 'F', 'quandl', '2017-01-01', '2017-02-01') +@pytest.mark.xfail(reaason="downstream install issue") def test_geopandas(): geopandas = import_module('geopandas') # noqa From 9d4691c7c94cf1470f05c1d863a10916e1cc33d4 Mon Sep 17 00:00:00 2001 From: Jeff Reback Date: Sun, 13 May 2018 19:34:37 -0400 Subject: [PATCH 3/4] ENH: add in extension dtype registry --- doc/source/whatsnew/v0.24.0.txt | 11 ++- pandas/core/algorithms.py | 4 +- pandas/core/arrays/base.py | 45 +++++++++- pandas/core/arrays/categorical.py | 4 + pandas/core/dtypes/base.py | 6 ++ pandas/core/dtypes/cast.py | 5 ++ pandas/core/dtypes/common.py | 39 ++------- pandas/core/dtypes/dtypes.py | 86 +++++++++++++++++++ pandas/core/internals.py | 21 +++-- pandas/core/series.py | 8 +- pandas/io/formats/format.py | 1 - pandas/tests/dtypes/test_dtypes.py | 23 ++++- pandas/tests/extension/base/__init__.py | 1 + pandas/tests/extension/base/constructors.py | 12 +++ pandas/tests/extension/base/methods.py | 3 +- pandas/tests/extension/base/missing.py | 5 ++ pandas/tests/extension/base/ops.py | 6 ++ pandas/tests/extension/base/reshaping.py | 9 ++ .../extension/category/test_categorical.py | 4 + pandas/tests/extension/decimal/array.py | 7 +- .../tests/extension/decimal/test_decimal.py | 14 ++- pandas/tests/extension/json/array.py | 7 +- pandas/tests/extension/json/test_json.py | 10 ++- 23 files changed, 273 insertions(+), 58 deletions(-) create mode 100644 pandas/tests/extension/base/ops.py diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index b94377af770f4..dbe7faefed69e 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -14,7 +14,6 @@ Other Enhancements ^^^^^^^^^^^^^^^^^^ - - -- .. _whatsnew_0240.api_breaking: @@ -22,6 +21,15 @@ Other Enhancements Backwards incompatible API changes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.. _whatsnew_0240.api.extension: + +ExtensionType Changes +^^^^^^^^^^^^^^^^^^^^^ + +- ``ExtensionArray`` has gained the abstract methods ``.dropna()`` and ``.append()``, and attribute ``array_type`` (:issue:`21185`) +- ``ExtensionDtype`` has gained the ability to instantiate from string dtypes, e.g. ``decimal`` would instaniate a registered ``DecimalDtype`` (:issue:`21185`) +- The ``ExtensionArray`` constructor, ``_from_sequence`` now take the keyword arg ``copy=False`` (:issue:`21185`) + .. _whatsnew_0240.api.other: Other API Changes @@ -177,4 +185,3 @@ Other - - - - diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index 88bc497f9f22d..eef2fde4386d8 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.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 1922801c30719..781118723a7c6 100644 --- a/pandas/core/arrays/base.py +++ b/pandas/core/arrays/base.py @@ -36,7 +36,9 @@ class ExtensionArray(object): * isna * take * copy + * append * _concat_same_type + * array_type An additional method is available to satisfy pandas' internal, private block API. @@ -49,6 +51,7 @@ class ExtensionArray(object): methods: * fillna + * dropna * unique * factorize / _values_for_factorize * argsort / _values_for_argsort @@ -82,7 +85,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 @@ -90,6 +93,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 True + if True, copy the underlying data Returns ------- ExtensionArray @@ -379,6 +384,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. @@ -567,6 +582,34 @@ def copy(self, deep=False): """ raise AbstractMethodError(self) + def append(self, other): + """ + Append a collection of Arrays together + + Parameters + ---------- + other : ExtensionArray or list/tuple of ExtensionArrays + + Returns + ------- + appended : ExtensionArray + """ + + to_concat = [self] + cls = self.__class__ + + if isinstance(other, (list, tuple)): + to_concat = to_concat + list(other) + else: + to_concat.append(other) + + for obj in to_concat: + if not isinstance(obj, cls): + raise TypeError('all inputs must be of type {}'.format( + cls.__name__)) + + return cls._concat_same_type(to_concat) + # ------------------------------------------------------------------------ # Block-related methods # ------------------------------------------------------------------------ diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index abcb9ae3494b5..63b99ffa06b8a 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -2343,6 +2343,10 @@ def isin(self, values): return algorithms.isin(self.codes, code_values) +# inform the Dtype about us +CategoricalDtype.array_type = Categorical + + # The Series.cat accessor diff --git a/pandas/core/dtypes/base.py b/pandas/core/dtypes/base.py index 49e98c16c716e..ba359c9ef4982 100644 --- a/pandas/core/dtypes/base.py +++ b/pandas/core/dtypes/base.py @@ -156,6 +156,12 @@ def name(self): """ raise AbstractMethodError(self) + @property + def array_type(self): + """Return the array type associated with this dtype + """ + raise AbstractMethodError(self) + @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 e4ed6d544d42e..73176887ca0d9 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -647,6 +647,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 c45838e6040a9..37d260088c4d4 100644 --- a/pandas/core/dtypes/common.py +++ b/pandas/core/dtypes/common.py @@ -9,7 +9,7 @@ DatetimeTZDtype, DatetimeTZDtypeType, PeriodDtype, PeriodDtypeType, IntervalDtype, IntervalDtypeType, - ExtensionDtype, PandasExtensionDtype) + ExtensionDtype, registry) from .generic import (ABCCategorical, ABCPeriodIndex, ABCDatetimeIndex, ABCSeries, ABCSparseArray, ABCSparseSeries, ABCCategoricalIndex, @@ -1975,38 +1975,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 708f54f5ca75b..94388103f1953 100644 --- a/pandas/core/dtypes/dtypes.py +++ b/pandas/core/dtypes/dtypes.py @@ -2,12 +2,70 @@ import re import numpy as np +from collections import OrderedDict from pandas import compat from pandas.core.dtypes.generic import ABCIndexClass, ABCCategoricalIndex from .base import ExtensionDtype, _DtypeOpsMixin +class Registry(object): + """ Registry for dtype inference + + We can directly construct dtypes in pandas_dtypes if they are + a type; the registry allows us to register an extension dtype + to try inference from a string or a dtype class + + These are tried in order for inference. + """ + dtypes = OrderedDict() + + @classmethod + def register(self, dtype, constructor=None): + """ + Parameters + ---------- + dtype : PandasExtension Dtype + """ + if not issubclass(dtype, (PandasExtensionDtype, ExtensionDtype)): + raise ValueError("can only register pandas extension dtypes") + + if constructor is None: + constructor = dtype.construct_from_string + + self.dtypes[dtype] = constructor + + 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, constructor in self.dtypes.items(): + try: + return constructor(dtype) + except TypeError: + pass + + return None + + +registry = Registry() + + class PandasExtensionDtype(_DtypeOpsMixin): """ A np.dtype duck-typed class, suitable for holding a custom dtype. @@ -564,6 +622,17 @@ def construct_from_string(cls, string): pass raise TypeError("could not construct PeriodDtype") + @classmethod + def construct_from_string_strict(cls, string): + """ + Strict construction from a string, raise a TypeError if not + possible + """ + if string.startswith('period[') or string.startswith('Period['): + # do not parse string like U as period[U] + return PeriodDtype.construct_from_string(string) + raise TypeError("could not construct PeriodDtype") + def __unicode__(self): return "period[{freq}]".format(freq=self.freq.freqstr) @@ -683,6 +752,16 @@ def construct_from_string(cls, string): msg = "a string needs to be passed, got type {typ}" raise TypeError(msg.format(typ=type(string))) + @classmethod + def construct_from_string_strict(cls, string): + """ + Strict construction from a string, raise a TypeError if not + possible + """ + if string.startswith('interval') or string.startswith('Interval'): + return IntervalDtype.construct_from_string(string) + raise TypeError("cannot construct IntervalDtype") + def __unicode__(self): if self.subtype is None: return "interval" @@ -723,3 +802,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, PeriodDtype.construct_from_string_strict) +registry.register(IntervalDtype, IntervalDtype.construct_from_string_strict) +registry.register(CategoricalDtype) diff --git a/pandas/core/internals.py b/pandas/core/internals.py index fe508dc1bb0bc..a5e9107b8a660 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) @@ -3170,6 +3177,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 @@ -3179,10 +3190,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 c9329e8b9e572..d27d5ab6afe8c 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -4055,11 +4055,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.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 12201f62946ac..adb4bf3f47572 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 cc833af03ae66..6c353283ba2db 100644 --- a/pandas/tests/dtypes/test_dtypes.py +++ b/pandas/tests/dtypes/test_dtypes.py @@ -12,7 +12,7 @@ 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, @@ -767,3 +767,24 @@ 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()), + ('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/__init__.py b/pandas/tests/extension/base/__init__.py index 9da985625c4ee..1f42de6737528 100644 --- a/pandas/tests/extension/base/__init__.py +++ b/pandas/tests/extension/base/__init__.py @@ -45,6 +45,7 @@ class TestMyDtype(BaseDtypeTests): from .dtype import BaseDtypeTests # noqa from .getitem import BaseGetitemTests # noqa from .groupby import BaseGroupbyTests # noqa +from .ops import BaseOpsTests # noqa from .interface import BaseInterfaceTests # noqa from .methods import BaseMethodsTests # noqa from .missing import BaseMissingTests # noqa diff --git a/pandas/tests/extension/base/constructors.py b/pandas/tests/extension/base/constructors.py index 489a430bb4020..972ef7f37acca 100644 --- a/pandas/tests/extension/base/constructors.py +++ b/pandas/tests/extension/base/constructors.py @@ -1,5 +1,6 @@ import pytest +import numpy as np import pandas as pd import pandas.util.testing as tm from pandas.core.internals import ExtensionBlock @@ -45,3 +46,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(np.array(data), dtype=dtype) + self.assert_series_equal(result, expected) + + result = pd.Series(np.array(data), dtype=str(dtype)) + self.assert_series_equal(result, expected) diff --git a/pandas/tests/extension/base/methods.py b/pandas/tests/extension/base/methods.py index c5436aa731d50..0ad3196277c34 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/ops.py b/pandas/tests/extension/base/ops.py new file mode 100644 index 0000000000000..3742f342e4346 --- /dev/null +++ b/pandas/tests/extension/base/ops.py @@ -0,0 +1,6 @@ +from .base import BaseExtensionTests + + +class BaseOpsTests(BaseExtensionTests): + """Various Series and DataFrame ops methos.""" + pass diff --git a/pandas/tests/extension/base/reshaping.py b/pandas/tests/extension/base/reshaping.py index fe920a47ab740..ff739c97f2785 100644 --- a/pandas/tests/extension/base/reshaping.py +++ b/pandas/tests/extension/base/reshaping.py @@ -26,6 +26,14 @@ def test_concat(self, data, in_frame): assert dtype == data.dtype assert isinstance(result._data.blocks[0], ExtensionBlock) + def test_append(self, data): + + wrapped = pd.Series(data) + result = wrapped.append(wrapped) + expected = pd.concat([wrapped, wrapped]) + + self.assert_series_equal(result, expected) + @pytest.mark.parametrize('in_frame', [True, False]) def test_concat_all_na_block(self, data_missing, in_frame): valid_block = pd.Series(data_missing.take([1, 1]), index=[0, 1]) @@ -84,6 +92,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 530a4e7a22a7a..c4928d026ca70 100644 --- a/pandas/tests/extension/category/test_categorical.py +++ b/pandas/tests/extension/category/test_categorical.py @@ -55,6 +55,10 @@ class TestDtype(base.BaseDtypeTests): pass +class TestOps(base.BaseOpsTests): + pass + + class TestInterface(base.BaseInterfaceTests): @pytest.mark.skip(reason="Memory usage doesn't match") def test_memory_usage(self): diff --git a/pandas/tests/extension/decimal/array.py b/pandas/tests/extension/decimal/array.py index 90f0181beab0d..641a691d07d58 100644 --- a/pandas/tests/extension/decimal/array.py +++ b/pandas/tests/extension/decimal/array.py @@ -27,7 +27,7 @@ def construct_from_string(cls, string): class DecimalArray(ExtensionArray): dtype = DecimalDtype() - def __init__(self, values): + def __init__(self, values, copy=False): assert all(isinstance(v, decimal.Decimal) for v in values) values = np.asarray(values, dtype=object) @@ -40,7 +40,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 @@ -101,5 +101,8 @@ def _concat_same_type(cls, to_concat): return cls(np.concatenate([x._data for x in to_concat])) +DecimalDtype.array_type = DecimalArray + + def make_data(): return [decimal.Decimal(random.random()) for _ in range(100)] diff --git a/pandas/tests/extension/decimal/test_decimal.py b/pandas/tests/extension/decimal/test_decimal.py index 1f8cf0264f62f..86b902c5309c1 100644 --- a/pandas/tests/extension/decimal/test_decimal.py +++ b/pandas/tests/extension/decimal/test_decimal.py @@ -99,10 +99,18 @@ class TestInterface(BaseDecimal, base.BaseInterfaceTests): pass -class TestConstructors(BaseDecimal, base.BaseConstructorsTests): +class TestOps(BaseDecimal, base.BaseOpsTests): pass +class TestConstructors(BaseDecimal, base.BaseConstructorsTests): + + @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): pass @@ -147,6 +155,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 10be7836cb8d7..97d579b362ee2 100644 --- a/pandas/tests/extension/json/array.py +++ b/pandas/tests/extension/json/array.py @@ -44,7 +44,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 @@ -58,7 +58,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 @@ -171,6 +171,9 @@ def _values_for_argsort(self): return np.array(frozen, dtype=object)[1:] +JSONDtype.array_type = JSONArray + + def make_data(): # TODO: Use a regular dict. See _NDFrameIndexer._setitem_with_indexer return [collections.UserDict([ diff --git a/pandas/tests/extension/json/test_json.py b/pandas/tests/extension/json/test_json.py index b7ac8033f3f6d..fd1010ff45e96 100644 --- a/pandas/tests/extension/json/test_json.py +++ b/pandas/tests/extension/json/test_json.py @@ -129,10 +129,18 @@ def test_custom_asserts(self): self.assert_frame_equal(a.to_frame(), b.to_frame()) -class TestConstructors(BaseJSON, base.BaseConstructorsTests): +class TestOps(BaseJSON, base.BaseOpsTests): pass +class TestConstructors(BaseJSON, base.BaseConstructorsTests): + + @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): pass From f5a0c2489a456770ae40e26ce853363212fc52b0 Mon Sep 17 00:00:00 2001 From: Jeff Reback Date: Thu, 24 May 2018 18:43:51 -0400 Subject: [PATCH 4/4] review comments --- doc/source/whatsnew/v0.24.0.txt | 2 +- pandas/core/arrays/base.py | 1 - pandas/core/dtypes/base.py | 8 +++++ pandas/core/dtypes/dtypes.py | 56 ++++++++++-------------------- pandas/core/indexes/interval.py | 2 +- pandas/tests/extension/base/ops.py | 6 ---- 6 files changed, 29 insertions(+), 46 deletions(-) delete mode 100644 pandas/tests/extension/base/ops.py diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index dbe7faefed69e..53a7396065a8d 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -27,7 +27,7 @@ ExtensionType Changes ^^^^^^^^^^^^^^^^^^^^^ - ``ExtensionArray`` has gained the abstract methods ``.dropna()`` and ``.append()``, and attribute ``array_type`` (:issue:`21185`) -- ``ExtensionDtype`` has gained the ability to instantiate from string dtypes, e.g. ``decimal`` would instaniate a registered ``DecimalDtype`` (:issue:`21185`) +- ``ExtensionDtype`` has gained the ability to instantiate from string dtypes, e.g. ``decimal`` would instantiate a registered ``DecimalDtype`` (:issue:`21185`) - The ``ExtensionArray`` constructor, ``_from_sequence`` now take the keyword arg ``copy=False`` (:issue:`21185`) .. _whatsnew_0240.api.other: diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py index 781118723a7c6..ca077bd89434f 100644 --- a/pandas/core/arrays/base.py +++ b/pandas/core/arrays/base.py @@ -38,7 +38,6 @@ class ExtensionArray(object): * copy * append * _concat_same_type - * array_type An additional method is available to satisfy pandas' internal, private block API. diff --git a/pandas/core/dtypes/base.py b/pandas/core/dtypes/base.py index ba359c9ef4982..701863a2595aa 100644 --- a/pandas/core/dtypes/base.py +++ b/pandas/core/dtypes/base.py @@ -109,6 +109,12 @@ class ExtensionDtype(_DtypeOpsMixin): * name * construct_from_string + + Optionally one can assign an array_type for construction with the name + of this dtype via the Registry + + * 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. @@ -118,6 +124,8 @@ class ExtensionDtype(_DtypeOpsMixin): provided for registering virtual subclasses. """ + array_type = None + def __str__(self): return self.name diff --git a/pandas/core/dtypes/dtypes.py b/pandas/core/dtypes/dtypes.py index 94388103f1953..8a5f1b5f885bf 100644 --- a/pandas/core/dtypes/dtypes.py +++ b/pandas/core/dtypes/dtypes.py @@ -2,7 +2,6 @@ import re import numpy as np -from collections import OrderedDict from pandas import compat from pandas.core.dtypes.generic import ABCIndexClass, ABCCategoricalIndex @@ -18,22 +17,19 @@ class Registry(object): These are tried in order for inference. """ - dtypes = OrderedDict() + dtypes = [] @classmethod - def register(self, dtype, constructor=None): + def register(self, dtype): """ Parameters ---------- - dtype : PandasExtension Dtype + dtype : ExtensionDtype """ if not issubclass(dtype, (PandasExtensionDtype, ExtensionDtype)): raise ValueError("can only register pandas extension dtypes") - if constructor is None: - constructor = dtype.construct_from_string - - self.dtypes[dtype] = constructor + self.dtypes.append(dtype) def find(self, dtype): """ @@ -54,9 +50,9 @@ def find(self, dtype): return None - for dtype_type, constructor in self.dtypes.items(): + for dtype_type in self.dtypes: try: - return constructor(dtype) + return dtype_type.construct_from_string(dtype) except TypeError: pass @@ -610,11 +606,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) @@ -622,17 +623,6 @@ def construct_from_string(cls, string): pass raise TypeError("could not construct PeriodDtype") - @classmethod - def construct_from_string_strict(cls, string): - """ - Strict construction from a string, raise a TypeError if not - possible - """ - if string.startswith('period[') or string.startswith('Period['): - # do not parse string like U as period[U] - return PeriodDtype.construct_from_string(string) - raise TypeError("could not construct PeriodDtype") - def __unicode__(self): return "period[{freq}]".format(freq=self.freq.freqstr) @@ -747,21 +737,13 @@ 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))) - @classmethod - def construct_from_string_strict(cls, string): - """ - Strict construction from a string, raise a TypeError if not - possible - """ - if string.startswith('interval') or string.startswith('Interval'): - return IntervalDtype.construct_from_string(string) - raise TypeError("cannot construct IntervalDtype") - def __unicode__(self): if self.subtype is None: return "interval" @@ -806,6 +788,6 @@ def is_dtype(cls, dtype): # register the dtypes in search order registry.register(DatetimeTZDtype) -registry.register(PeriodDtype, PeriodDtype.construct_from_string_strict) -registry.register(IntervalDtype, IntervalDtype.construct_from_string_strict) +registry.register(PeriodDtype) +registry.register(IntervalDtype) registry.register(CategoricalDtype) diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py index 8f8d8760583ce..2694f5d5be384 100644 --- a/pandas/core/indexes/interval.py +++ b/pandas/core/indexes/interval.py @@ -800,7 +800,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(str(self.left.dtype)) @property def inferred_type(self): diff --git a/pandas/tests/extension/base/ops.py b/pandas/tests/extension/base/ops.py deleted file mode 100644 index 3742f342e4346..0000000000000 --- a/pandas/tests/extension/base/ops.py +++ /dev/null @@ -1,6 +0,0 @@ -from .base import BaseExtensionTests - - -class BaseOpsTests(BaseExtensionTests): - """Various Series and DataFrame ops methos.""" - pass