Skip to content

Commit b957f6f

Browse files
m-charltonjorisvandenbossche
authored andcommitted
API/DEPR: change raise_on_error kwarg with errors kwarg in astype #14878 (#14967)
1 parent 136a6fb commit b957f6f

File tree

6 files changed

+58
-16
lines changed

6 files changed

+58
-16
lines changed

doc/source/whatsnew/v0.20.0.txt

+1-1
Original file line numberDiff line numberDiff line change
@@ -258,7 +258,7 @@ Deprecations
258258
- ``Index.repeat()`` and ``MultiIndex.repeat()`` have deprecated the ``n`` parameter in favor of ``repeats`` (:issue:`12662`)
259259
- ``Categorical.searchsorted()`` and ``Series.searchsorted()`` have deprecated the ``v`` parameter in favor of ``value`` (:issue:`12662`)
260260
- ``TimedeltaIndex.searchsorted()``, ``DatetimeIndex.searchsorted()``, and ``PeriodIndex.searchsorted()`` have deprecated the ``key`` parameter in favor of ``value`` (:issue:`12662`)
261-
261+
- ``DataFrame.astype()`` has deprecated the ``raise_on_error`` parameter in favor of ``errors`` (:issue:`14878`)
262262

263263

264264

pandas/core/generic.py

+15-5
Original file line numberDiff line numberDiff line change
@@ -3061,7 +3061,9 @@ def blocks(self):
30613061
"""Internal property, property synonym for as_blocks()"""
30623062
return self.as_blocks()
30633063

3064-
def astype(self, dtype, copy=True, raise_on_error=True, **kwargs):
3064+
@deprecate_kwarg(old_arg_name='raise_on_error', new_arg_name='errors',
3065+
mapping={True: 'raise', False: 'ignore'})
3066+
def astype(self, dtype, copy=True, errors='raise', **kwargs):
30653067
"""
30663068
Cast object to input numpy.dtype
30673069
Return a copy when copy = True (be really careful with this!)
@@ -3073,7 +3075,15 @@ def astype(self, dtype, copy=True, raise_on_error=True, **kwargs):
30733075
the same type. Alternatively, use {col: dtype, ...}, where col is a
30743076
column label and dtype is a numpy.dtype or Python type to cast one
30753077
or more of the DataFrame's columns to column-specific types.
3076-
raise_on_error : raise on invalid input
3078+
errors : {'raise', 'ignore'}, default 'raise'.
3079+
Control raising of exceptions on invalid data for provided dtype.
3080+
3081+
- ``raise`` : allow exceptions to be raised
3082+
- ``ignore`` : suppress exceptions. On error return original object
3083+
3084+
.. versionadded:: 0.20.0
3085+
3086+
raise_on_error : DEPRECATED use ``errors`` instead
30773087
kwargs : keyword arguments to pass on to the constructor
30783088
30793089
Returns
@@ -3086,7 +3096,7 @@ def astype(self, dtype, copy=True, raise_on_error=True, **kwargs):
30863096
raise KeyError('Only the Series name can be used for '
30873097
'the key in Series dtype mappings.')
30883098
new_type = list(dtype.values())[0]
3089-
return self.astype(new_type, copy, raise_on_error, **kwargs)
3099+
return self.astype(new_type, copy, errors, **kwargs)
30903100
elif self.ndim > 2:
30913101
raise NotImplementedError(
30923102
'astype() only accepts a dtype arg of type dict when '
@@ -3107,8 +3117,8 @@ def astype(self, dtype, copy=True, raise_on_error=True, **kwargs):
31073117
return concat(results, axis=1, copy=False)
31083118

31093119
# else, only a single dtype is given
3110-
new_data = self._data.astype(dtype=dtype, copy=copy,
3111-
raise_on_error=raise_on_error, **kwargs)
3120+
new_data = self._data.astype(dtype=dtype, copy=copy, errors=errors,
3121+
**kwargs)
31123122
return self._constructor(new_data).__finalize__(self)
31133123

31143124
def copy(self, deep=True):

pandas/core/internals.py

+13-7
Original file line numberDiff line numberDiff line change
@@ -455,17 +455,23 @@ def downcast(self, dtypes=None, mgr=None):
455455

456456
return blocks
457457

458-
def astype(self, dtype, copy=False, raise_on_error=True, values=None,
459-
**kwargs):
460-
return self._astype(dtype, copy=copy, raise_on_error=raise_on_error,
461-
values=values, **kwargs)
458+
def astype(self, dtype, copy=False, errors='raise', values=None, **kwargs):
459+
return self._astype(dtype, copy=copy, errors=errors, values=values,
460+
**kwargs)
462461

463-
def _astype(self, dtype, copy=False, raise_on_error=True, values=None,
462+
def _astype(self, dtype, copy=False, errors='raise', values=None,
464463
klass=None, mgr=None, **kwargs):
465464
"""
466465
Coerce to the new type (if copy=True, return a new copy)
467466
raise on an except if raise == True
468467
"""
468+
errors_legal_values = ('raise', 'ignore')
469+
470+
if errors not in errors_legal_values:
471+
invalid_arg = ("Expected value of kwarg 'errors' to be one of {}. "
472+
"Supplied value is '{}'".format(
473+
list(errors_legal_values), errors))
474+
raise ValueError(invalid_arg)
469475

470476
# may need to convert to categorical
471477
# this is only called for non-categoricals
@@ -507,7 +513,7 @@ def _astype(self, dtype, copy=False, raise_on_error=True, values=None,
507513
newb = make_block(values, placement=self.mgr_locs, dtype=dtype,
508514
klass=klass)
509515
except:
510-
if raise_on_error is True:
516+
if errors == 'raise':
511517
raise
512518
newb = self.copy() if copy else self
513519

@@ -2147,7 +2153,7 @@ def take_nd(self, indexer, axis=0, new_mgr_locs=None, fill_tuple=None):
21472153

21482154
return self.make_block_same_class(new_values, new_mgr_locs)
21492155

2150-
def _astype(self, dtype, copy=False, raise_on_error=True, values=None,
2156+
def _astype(self, dtype, copy=False, errors='raise', values=None,
21512157
klass=None, mgr=None):
21522158
"""
21532159
Coerce to the new type (if copy=True, return a new copy)

pandas/tests/frame/test_dtypes.py

+15-2
Original file line numberDiff line numberDiff line change
@@ -357,15 +357,15 @@ def test_astype_with_exclude_string(self):
357357
df = self.frame.copy()
358358
expected = self.frame.astype(int)
359359
df['string'] = 'foo'
360-
casted = df.astype(int, raise_on_error=False)
360+
casted = df.astype(int, errors='ignore')
361361

362362
expected['string'] = 'foo'
363363
assert_frame_equal(casted, expected)
364364

365365
df = self.frame.copy()
366366
expected = self.frame.astype(np.int32)
367367
df['string'] = 'foo'
368-
casted = df.astype(np.int32, raise_on_error=False)
368+
casted = df.astype(np.int32, errors='ignore')
369369

370370
expected['string'] = 'foo'
371371
assert_frame_equal(casted, expected)
@@ -523,6 +523,19 @@ def test_timedeltas(self):
523523
result = df.get_dtype_counts().sort_values()
524524
assert_series_equal(result, expected)
525525

526+
def test_arg_for_errors_in_astype(self):
527+
# issue #14878
528+
529+
df = DataFrame([1, 2, 3])
530+
531+
with self.assertRaises(ValueError):
532+
df.astype(np.float64, errors=True)
533+
534+
with tm.assert_produces_warning(FutureWarning):
535+
df.astype(np.int8, raise_on_error=False)
536+
537+
df.astype(np.int8, errors='ignore')
538+
526539

527540
class TestDataFrameDatetimeWithTZ(tm.TestCase, TestData):
528541

pandas/tests/series/test_dtypes.py

+13
Original file line numberDiff line numberDiff line change
@@ -168,3 +168,16 @@ def test_complexx(self):
168168
b.real = np.arange(5) + 5
169169
tm.assert_numpy_array_equal(a + 5, b.real)
170170
tm.assert_numpy_array_equal(4 * a, b.imag)
171+
172+
def test_arg_for_errors_in_astype(self):
173+
# issue #14878
174+
175+
sr = Series([1, 2, 3])
176+
177+
with self.assertRaises(ValueError):
178+
sr.astype(np.float64, errors=False)
179+
180+
with tm.assert_produces_warning(FutureWarning):
181+
sr.astype(np.int8, raise_on_error=True)
182+
183+
sr.astype(np.int8, errors='raise')

pandas/tests/test_internals.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -553,7 +553,7 @@ def test_astype(self):
553553
'e: f4; f: f2; g: f8')
554554
for t in ['float16', 'float32', 'float64', 'int32', 'int64']:
555555
t = np.dtype(t)
556-
tmgr = mgr.astype(t, raise_on_error=False)
556+
tmgr = mgr.astype(t, errors='ignore')
557557
self.assertEqual(tmgr.get('c').dtype.type, t)
558558
self.assertEqual(tmgr.get('e').dtype.type, t)
559559
self.assertEqual(tmgr.get('f').dtype.type, t)

0 commit comments

Comments
 (0)