File tree Expand file tree Collapse file tree 2 files changed +64
-0
lines changed
Expand file tree Collapse file tree 2 files changed +64
-0
lines changed Original file line number Diff line number Diff line change 11"""An interface for extending pandas with custom arrays."""
2+ import numpy as np
3+
24from pandas .errors import AbstractMethodError
35
46_not_implemented_message = "{} does not implement {}."
@@ -138,6 +140,34 @@ def nbytes(self):
138140 # ------------------------------------------------------------------------
139141 # Additional Methods
140142 # ------------------------------------------------------------------------
143+ def astype (self , dtype , copy = True ):
144+ """Cast to a NumPy array with 'dtype'.
145+
146+ The default implementation only allows casting to 'object' dtype.
147+
148+ Parameters
149+ ----------
150+ dtype : str or dtype
151+ Typecode or data-type to which the array is cast.
152+ copy : bool, default True
153+ Whether to copy the data, even if not necessary. If False,
154+ a copy is made only if the old dtype does not match the
155+ new dtype.
156+
157+ Returns
158+ -------
159+ array : ndarray
160+ NumPy ndarray with 'dtype' for its dtype.
161+ """
162+ np_dtype = np .dtype (dtype )
163+
164+ if np_dtype != 'object' :
165+ msg = ("{} can only be coerced to 'object' dtype, "
166+ "not '{}'." ).format (type (self ).__name__ , dtype )
167+ raise ValueError (msg )
168+
169+ return np .array (self , dtype = np_dtype , copy = copy )
170+
141171 def isna (self ):
142172 # type: () -> np.ndarray
143173 """Boolean NumPy array indicating if each value is missing.
Original file line number Diff line number Diff line change 1+ import numpy as np
2+
3+ import pandas .util .testing as tm
4+ from pandas .core .arrays import ExtensionArray
5+
6+
7+ class DummyArray (ExtensionArray ):
8+
9+ def __init__ (self , data ):
10+ self .data = data
11+
12+ def __array__ (self , dtype ):
13+ return self .data
14+
15+
16+ def test_astype ():
17+ arr = DummyArray (np .array ([1 , 2 , 3 ]))
18+ expected = np .array ([1 , 2 , 3 ], dtype = object )
19+
20+ result = arr .astype (object )
21+ tm .assert_numpy_array_equal (result , expected )
22+
23+ result = arr .astype ('object' )
24+ tm .assert_numpy_array_equal (result , expected )
25+
26+
27+ def test_astype_raises ():
28+ arr = DummyArray (np .array ([1 , 2 , 3 ]))
29+
30+ xpr = ("DummyArray can only be coerced to 'object' dtype, not "
31+ "'<class 'int'>'" )
32+
33+ with tm .assert_raises_regex (ValueError , xpr ):
34+ arr .astype (int )
You can’t perform that action at this time.
0 commit comments