Skip to content

Commit

Permalink
API: Default ExtensionArray.astype
Browse files Browse the repository at this point in the history
(cherry picked from commit 943a915562b72bed147c857de927afa0daf31c1a)
  • Loading branch information
TomAugspurger committed Feb 8, 2018
1 parent b835127 commit fbf0a06
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
30 changes: 30 additions & 0 deletions pandas/core/arrays/base.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
"""An interface for extending pandas with custom arrays."""
import numpy as np

from pandas.errors import AbstractMethodError

_not_implemented_message = "{} does not implement {}."
Expand Down Expand Up @@ -138,6 +140,34 @@ def nbytes(self):
# ------------------------------------------------------------------------
# Additional Methods
# ------------------------------------------------------------------------
def astype(self, dtype, copy=True):
"""Cast to a NumPy array with 'dtype'.
The default implementation only allows casting to 'object' dtype.
Parameters
----------
dtype : str or dtype
Typecode or data-type to which the array is cast.
copy : bool, default True
Whether to copy the data, even if not necessary. If False,
a copy is made only if the old dtype does not match the
new dtype.
Returns
-------
array : ndarray
NumPy ndarray with 'dtype' for its dtype.
"""
np_dtype = np.dtype(dtype)

if np_dtype != 'object':
msg = ("{} can only be coerced to 'object' dtype, "
"not '{}'.").format(type(self).__name__, dtype)
raise ValueError(msg)

return np.array(self, dtype=np_dtype, copy=copy)

def isna(self):
# type: () -> np.ndarray
"""Boolean NumPy array indicating if each value is missing.
Expand Down
34 changes: 34 additions & 0 deletions pandas/tests/extension_arrays/test_common.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import numpy as np

import pandas.util.testing as tm
from pandas.core.arrays import ExtensionArray


class DummyArray(ExtensionArray):

def __init__(self, data):
self.data = data

def __array__(self, dtype):
return self.data


def test_astype():
arr = DummyArray(np.array([1, 2, 3]))
expected = np.array([1, 2, 3], dtype=object)

result = arr.astype(object)
tm.assert_numpy_array_equal(result, expected)

result = arr.astype('object')
tm.assert_numpy_array_equal(result, expected)


def test_astype_raises():
arr = DummyArray(np.array([1, 2, 3]))

xpr = ("DummyArray can only be coerced to 'object' dtype, not "
"'<class 'int'>'")

with tm.assert_raises_regex(ValueError, xpr):
arr.astype(int)

0 comments on commit fbf0a06

Please sign in to comment.