Skip to content

Commit d188ef9

Browse files
jrebackalanbato
authored andcommitted
DEPR: deprecate raise_on_error in .where/.mask in favor of errors= (pandas-dev#17744)
closes pandas-dev#14968
1 parent 2ad0480 commit d188ef9

File tree

12 files changed

+108
-69
lines changed

12 files changed

+108
-69
lines changed

doc/source/whatsnew/v0.21.0.txt

+2-1
Original file line numberDiff line numberDiff line change
@@ -665,8 +665,9 @@ Deprecations
665665
- ``pd.TimeGrouper`` is deprecated in favor of :class:`pandas.Grouper` (:issue:`16747`)
666666
- ``cdate_range`` has been deprecated in favor of :func:`bdate_range`, which has gained ``weekmask`` and ``holidays`` parameters for building custom frequency date ranges. See the :ref:`documentation <timeseries.custom-freq-ranges>` for more details (:issue:`17596`)
667667
- passing ``categories`` or ``ordered`` kwargs to :func:`Series.astype` is deprecated, in favor of passing a :ref:`CategoricalDtype <whatsnew_0210.enhancements.categorical_dtype>` (:issue:`17636`)
668-
- Passing a non-existent column in ``.to_excel(..., columns=)`` is deprecated and will raise a ``KeyError`` in the future (:issue:`17295`)
669668
- ``.get_value`` and ``.set_value`` on ``Series``, ``DataFrame``, ``Panel``, ``SparseSeries``, and ``SparseDataFrame`` are deprecated in favor of using ``.iat[]`` or ``.at[]`` accessors (:issue:`15269`)
669+
- Passing a non-existant column in ``.to_excel(..., columns=)`` is deprecated and will raise a ``KeyError`` in the future (:issue:`17295`)
670+
- ``raise_on_error`` parameter to :func:`Series.where`, :func:`Series.mask`, :func:`DataFrame.where`, :func:`DataFrame.mask` is deprecated, in favor of ``errors=`` (:issue:`14968`)
670671

671672
.. _whatsnew_0210.deprecations.select:
672673

pandas/core/computation/expressions.py

+14-24
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ def set_numexpr_threads(n=None):
5656
ne.set_num_threads(n)
5757

5858

59-
def _evaluate_standard(op, op_str, a, b, raise_on_error=True, **eval_kwargs):
59+
def _evaluate_standard(op, op_str, a, b, **eval_kwargs):
6060
""" standard evaluation """
6161
if _TEST_MODE:
6262
_store_test_result(False)
@@ -89,7 +89,7 @@ def _can_use_numexpr(op, op_str, a, b, dtype_check):
8989
return False
9090

9191

92-
def _evaluate_numexpr(op, op_str, a, b, raise_on_error=False, truediv=True,
92+
def _evaluate_numexpr(op, op_str, a, b, truediv=True,
9393
reversed=False, **eval_kwargs):
9494
result = None
9595

@@ -111,25 +111,22 @@ def _evaluate_numexpr(op, op_str, a, b, raise_on_error=False, truediv=True,
111111
except ValueError as detail:
112112
if 'unknown type object' in str(detail):
113113
pass
114-
except Exception as detail:
115-
if raise_on_error:
116-
raise
117114

118115
if _TEST_MODE:
119116
_store_test_result(result is not None)
120117

121118
if result is None:
122-
result = _evaluate_standard(op, op_str, a, b, raise_on_error)
119+
result = _evaluate_standard(op, op_str, a, b)
123120

124121
return result
125122

126123

127-
def _where_standard(cond, a, b, raise_on_error=True):
124+
def _where_standard(cond, a, b):
128125
return np.where(_values_from_object(cond), _values_from_object(a),
129126
_values_from_object(b))
130127

131128

132-
def _where_numexpr(cond, a, b, raise_on_error=False):
129+
def _where_numexpr(cond, a, b):
133130
result = None
134131

135132
if _can_use_numexpr(None, 'where', a, b, 'where'):
@@ -147,11 +144,10 @@ def _where_numexpr(cond, a, b, raise_on_error=False):
147144
if 'unknown type object' in str(detail):
148145
pass
149146
except Exception as detail:
150-
if raise_on_error:
151-
raise TypeError(str(detail))
147+
raise TypeError(str(detail))
152148

153149
if result is None:
154-
result = _where_standard(cond, a, b, raise_on_error)
150+
result = _where_standard(cond, a, b)
155151

156152
return result
157153

@@ -189,7 +185,7 @@ def _bool_arith_check(op_str, a, b, not_allowed=frozenset(('/', '//', '**')),
189185
return True
190186

191187

192-
def evaluate(op, op_str, a, b, raise_on_error=False, use_numexpr=True,
188+
def evaluate(op, op_str, a, b, use_numexpr=True,
193189
**eval_kwargs):
194190
""" evaluate and return the expression of the op on a and b
195191
@@ -200,19 +196,16 @@ def evaluate(op, op_str, a, b, raise_on_error=False, use_numexpr=True,
200196
op_str: the string version of the op
201197
a : left operand
202198
b : right operand
203-
raise_on_error : pass the error to the higher level if indicated
204-
(default is False), otherwise evaluate the op with and
205-
return the results
206199
use_numexpr : whether to try to use numexpr (default True)
207200
"""
201+
208202
use_numexpr = use_numexpr and _bool_arith_check(op_str, a, b)
209203
if use_numexpr:
210-
return _evaluate(op, op_str, a, b, raise_on_error=raise_on_error,
211-
**eval_kwargs)
212-
return _evaluate_standard(op, op_str, a, b, raise_on_error=raise_on_error)
204+
return _evaluate(op, op_str, a, b, **eval_kwargs)
205+
return _evaluate_standard(op, op_str, a, b)
213206

214207

215-
def where(cond, a, b, raise_on_error=False, use_numexpr=True):
208+
def where(cond, a, b, use_numexpr=True):
216209
""" evaluate the where condition cond on a and b
217210
218211
Parameters
@@ -221,15 +214,12 @@ def where(cond, a, b, raise_on_error=False, use_numexpr=True):
221214
cond : a boolean array
222215
a : return if cond is True
223216
b : return if cond is False
224-
raise_on_error : pass the error to the higher level if indicated
225-
(default is False), otherwise evaluate the op with and
226-
return the results
227217
use_numexpr : whether to try to use numexpr (default True)
228218
"""
229219

230220
if use_numexpr:
231-
return _where(cond, a, b, raise_on_error=raise_on_error)
232-
return _where_standard(cond, a, b, raise_on_error=raise_on_error)
221+
return _where(cond, a, b)
222+
return _where_standard(cond, a, b)
233223

234224

235225
def set_test_mode(v=True):

pandas/core/frame.py

+4-6
Original file line numberDiff line numberDiff line change
@@ -3862,9 +3862,9 @@ def _combine_match_columns(self, other, func, level=None,
38623862
try_cast=try_cast)
38633863
return self._constructor(new_data)
38643864

3865-
def _combine_const(self, other, func, raise_on_error=True, try_cast=True):
3865+
def _combine_const(self, other, func, errors='raise', try_cast=True):
38663866
new_data = self._data.eval(func=func, other=other,
3867-
raise_on_error=raise_on_error,
3867+
errors=errors,
38683868
try_cast=try_cast)
38693869
return self._constructor(new_data)
38703870

@@ -4035,8 +4035,7 @@ def combiner(x, y, needs_i8_conversion=False):
40354035
else:
40364036
mask = isna(x_values)
40374037

4038-
return expressions.where(mask, y_values, x_values,
4039-
raise_on_error=True)
4038+
return expressions.where(mask, y_values, x_values)
40404039

40414040
return self.combine(other, combiner, overwrite=False)
40424041

@@ -4091,8 +4090,7 @@ def update(self, other, join='left', overwrite=True, filter_func=None,
40914090
if mask.all():
40924091
continue
40934092

4094-
self[col] = expressions.where(mask, this, that,
4095-
raise_on_error=True)
4093+
self[col] = expressions.where(mask, this, that)
40964094

40974095
# ----------------------------------------------------------------------
40984096
# Misc methods

pandas/core/generic.py

+38-7
Original file line numberDiff line numberDiff line change
@@ -5758,7 +5758,7 @@ def _align_series(self, other, join='outer', axis=None, level=None,
57585758
return left.__finalize__(self), right.__finalize__(other)
57595759

57605760
def _where(self, cond, other=np.nan, inplace=False, axis=None, level=None,
5761-
try_cast=False, raise_on_error=True):
5761+
errors='raise', try_cast=False):
57625762
"""
57635763
Equivalent to public method `where`, except that `other` is not
57645764
applied as a function even if callable. Used in __setitem__.
@@ -5887,7 +5887,7 @@ def _where(self, cond, other=np.nan, inplace=False, axis=None, level=None,
58875887

58885888
else:
58895889
new_data = self._data.where(other=other, cond=cond, align=align,
5890-
raise_on_error=raise_on_error,
5890+
errors=errors,
58915891
try_cast=try_cast, axis=block_axis,
58925892
transpose=self._AXIS_REVERSED)
58935893

@@ -5924,12 +5924,21 @@ def _where(self, cond, other=np.nan, inplace=False, axis=None, level=None,
59245924
Whether to perform the operation in place on the data
59255925
axis : alignment axis if needed, default None
59265926
level : alignment level if needed, default None
5927+
errors : str, {'raise', 'ignore'}, default 'raise'
5928+
- ``raise`` : allow exceptions to be raised
5929+
- ``ignore`` : suppress exceptions. On error return original object
5930+
5931+
Note that currently this parameter won't affect
5932+
the results and will always coerce to a suitable dtype.
5933+
59275934
try_cast : boolean, default False
59285935
try to cast the result back to the input type (if possible),
59295936
raise_on_error : boolean, default True
59305937
Whether to raise on invalid data types (e.g. trying to where on
59315938
strings)
59325939
5940+
.. deprecated:: 0.21.0
5941+
59335942
Returns
59345943
-------
59355944
wh : same type as caller
@@ -6005,24 +6014,46 @@ def _where(self, cond, other=np.nan, inplace=False, axis=None, level=None,
60056014
cond_rev="False", name='where',
60066015
name_other='mask'))
60076016
def where(self, cond, other=np.nan, inplace=False, axis=None, level=None,
6008-
try_cast=False, raise_on_error=True):
6017+
errors='raise', try_cast=False, raise_on_error=None):
6018+
6019+
if raise_on_error is not None:
6020+
warnings.warn(
6021+
"raise_on_error is deprecated in "
6022+
"favor of errors='raise|ignore'",
6023+
FutureWarning, stacklevel=2)
6024+
6025+
if raise_on_error:
6026+
errors = 'raise'
6027+
else:
6028+
errors = 'ignore'
60096029

60106030
other = com._apply_if_callable(other, self)
6011-
return self._where(cond, other, inplace, axis, level, try_cast,
6012-
raise_on_error)
6031+
return self._where(cond, other, inplace, axis, level,
6032+
errors=errors, try_cast=try_cast)
60136033

60146034
@Appender(_shared_docs['where'] % dict(_shared_doc_kwargs, cond="False",
60156035
cond_rev="True", name='mask',
60166036
name_other='where'))
60176037
def mask(self, cond, other=np.nan, inplace=False, axis=None, level=None,
6018-
try_cast=False, raise_on_error=True):
6038+
errors='raise', try_cast=False, raise_on_error=None):
6039+
6040+
if raise_on_error is not None:
6041+
warnings.warn(
6042+
"raise_on_error is deprecated in "
6043+
"favor of errors='raise|ignore'",
6044+
FutureWarning, stacklevel=2)
6045+
6046+
if raise_on_error:
6047+
errors = 'raise'
6048+
else:
6049+
errors = 'ignore'
60196050

60206051
inplace = validate_bool_kwarg(inplace, 'inplace')
60216052
cond = com._apply_if_callable(cond, self)
60226053

60236054
return self.where(~cond, other=other, inplace=inplace, axis=axis,
60246055
level=level, try_cast=try_cast,
6025-
raise_on_error=raise_on_error)
6056+
errors=errors)
60266057

60276058
_shared_docs['shift'] = ("""
60286059
Shift index by desired number of periods with an optional time freq

pandas/core/internals.py

+27-16
Original file line numberDiff line numberDiff line change
@@ -533,10 +533,16 @@ def astype(self, dtype, copy=False, errors='raise', values=None, **kwargs):
533533
**kwargs)
534534

535535
def _astype(self, dtype, copy=False, errors='raise', values=None,
536-
klass=None, mgr=None, raise_on_error=False, **kwargs):
536+
klass=None, mgr=None, **kwargs):
537537
"""
538-
Coerce to the new type (if copy=True, return a new copy)
539-
raise on an except if raise == True
538+
Coerce to the new type
539+
540+
dtype : str, dtype convertible
541+
copy : boolean, default False
542+
copy if indicated
543+
errors : str, {'raise', 'ignore'}, default 'ignore'
544+
- ``raise`` : allow exceptions to be raised
545+
- ``ignore`` : suppress exceptions. On error return original object
540546
"""
541547
errors_legal_values = ('raise', 'ignore')
542548

@@ -1248,16 +1254,18 @@ def shift(self, periods, axis=0, mgr=None):
12481254

12491255
return [self.make_block(new_values, fastpath=True)]
12501256

1251-
def eval(self, func, other, raise_on_error=True, try_cast=False, mgr=None):
1257+
def eval(self, func, other, errors='raise', try_cast=False, mgr=None):
12521258
"""
12531259
evaluate the block; return result block from the result
12541260
12551261
Parameters
12561262
----------
12571263
func : how to combine self, other
12581264
other : a ndarray/object
1259-
raise_on_error : if True, raise when I can't perform the function,
1260-
False by default (and just return the data that we had coming in)
1265+
errors : str, {'raise', 'ignore'}, default 'raise'
1266+
- ``raise`` : allow exceptions to be raised
1267+
- ``ignore`` : suppress exceptions. On error return original object
1268+
12611269
try_cast : try casting the results to the input type
12621270
12631271
Returns
@@ -1295,7 +1303,7 @@ def eval(self, func, other, raise_on_error=True, try_cast=False, mgr=None):
12951303
except TypeError:
12961304
block = self.coerce_to_target_dtype(orig_other)
12971305
return block.eval(func, orig_other,
1298-
raise_on_error=raise_on_error,
1306+
errors=errors,
12991307
try_cast=try_cast, mgr=mgr)
13001308

13011309
# get the result, may need to transpose the other
@@ -1337,7 +1345,7 @@ def get_result(other):
13371345
# error handler if we have an issue operating with the function
13381346
def handle_error():
13391347

1340-
if raise_on_error:
1348+
if errors == 'raise':
13411349
# The 'detail' variable is defined in outer scope.
13421350
raise TypeError('Could not operate %s with block values %s' %
13431351
(repr(other), str(detail))) # noqa
@@ -1383,7 +1391,7 @@ def handle_error():
13831391
result = _block_shape(result, ndim=self.ndim)
13841392
return [self.make_block(result, fastpath=True, )]
13851393

1386-
def where(self, other, cond, align=True, raise_on_error=True,
1394+
def where(self, other, cond, align=True, errors='raise',
13871395
try_cast=False, axis=0, transpose=False, mgr=None):
13881396
"""
13891397
evaluate the block; return result block(s) from the result
@@ -1393,8 +1401,10 @@ def where(self, other, cond, align=True, raise_on_error=True,
13931401
other : a ndarray/object
13941402
cond : the condition to respect
13951403
align : boolean, perform alignment on other/cond
1396-
raise_on_error : if True, raise when I can't perform the function,
1397-
False by default (and just return the data that we had coming in)
1404+
errors : str, {'raise', 'ignore'}, default 'raise'
1405+
- ``raise`` : allow exceptions to be raised
1406+
- ``ignore`` : suppress exceptions. On error return original object
1407+
13981408
axis : int
13991409
transpose : boolean
14001410
Set to True if self is stored with axes reversed
@@ -1404,6 +1414,7 @@ def where(self, other, cond, align=True, raise_on_error=True,
14041414
a new block(s), the result of the func
14051415
"""
14061416
import pandas.core.computation.expressions as expressions
1417+
assert errors in ['raise', 'ignore']
14071418

14081419
values = self.values
14091420
orig_other = other
@@ -1436,9 +1447,9 @@ def func(cond, values, other):
14361447

14371448
try:
14381449
return self._try_coerce_result(expressions.where(
1439-
cond, values, other, raise_on_error=True))
1450+
cond, values, other))
14401451
except Exception as detail:
1441-
if raise_on_error:
1452+
if errors == 'raise':
14421453
raise TypeError('Could not operate [%s] with block values '
14431454
'[%s]' % (repr(other), str(detail)))
14441455
else:
@@ -1454,10 +1465,10 @@ def func(cond, values, other):
14541465
except TypeError:
14551466

14561467
# we cannot coerce, return a compat dtype
1457-
# we are explicity ignoring raise_on_error here
1468+
# we are explicity ignoring errors
14581469
block = self.coerce_to_target_dtype(other)
14591470
blocks = block.where(orig_other, cond, align=align,
1460-
raise_on_error=raise_on_error,
1471+
errors=errors,
14611472
try_cast=try_cast, axis=axis,
14621473
transpose=transpose)
14631474
return self._maybe_downcast(blocks, 'infer')
@@ -2745,7 +2756,7 @@ def sp_index(self):
27452756
def kind(self):
27462757
return self.values.kind
27472758

2748-
def _astype(self, dtype, copy=False, raise_on_error=True, values=None,
2759+
def _astype(self, dtype, copy=False, errors='raise', values=None,
27492760
klass=None, mgr=None, **kwargs):
27502761
if values is None:
27512762
values = self.values

0 commit comments

Comments
 (0)