Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CLN GH22873 Replace base excepts in pandas/core #22901

Merged
merged 1 commit into from
Oct 2, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion doc/source/whatsnew/v0.24.0.txt
Original file line number Diff line number Diff line change
Expand Up @@ -834,4 +834,3 @@ Other
- :meth:`DataFrame.nlargest` and :meth:`DataFrame.nsmallest` now returns the correct n values when keep != 'all' also when tied on the first columns (:issue:`22752`)
- :meth:`~pandas.io.formats.style.Styler.bar` now also supports tablewise application (in addition to rowwise and columnwise) with ``axis=None`` and setting clipping range with ``vmin`` and ``vmax`` (:issue:`21548` and :issue:`21526`). ``NaN`` values are also handled properly.
- Logical operations ``&, |, ^`` between :class:`Series` and :class:`Index` will no longer raise ``ValueError`` (:issue:`22092`)
-
2 changes: 1 addition & 1 deletion pandas/core/computation/pytables.py
Original file line number Diff line number Diff line change
Expand Up @@ -411,7 +411,7 @@ def visit_Subscript(self, node, **kwargs):
slobj = self.visit(node.slice)
try:
value = value.value
except:
except AttributeError:
pass

try:
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/dtypes/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -467,7 +467,7 @@ def is_timedelta64_dtype(arr_or_dtype):
return False
try:
tipo = _get_dtype_type(arr_or_dtype)
except:
except (TypeError, ValueError, SyntaxError):
return False
return issubclass(tipo, np.timedelta64)

Expand Down
8 changes: 4 additions & 4 deletions pandas/core/dtypes/dtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -358,11 +358,11 @@ def construct_from_string(cls, string):
try:
if string == 'category':
return cls()
except:
else:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this may have been it. For whatever reason, we're here with

ipdb> pp string
   A  A
0  0  2
1  2  4
2  0  4

We do

ipdb> string == 'category'
*** FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison

That FutureWarning is elevated to an error. I didn't realize this, but you can catch warnings, so the very simple fix is to also catch FutureWarning here, but that feels fragile. I'll investigate a better fix...

raise TypeError("cannot construct a CategoricalDtype")
except AttributeError:
pass

raise TypeError("cannot construct a CategoricalDtype")

@staticmethod
def validate_ordered(ordered):
"""
Expand Down Expand Up @@ -519,7 +519,7 @@ def __new__(cls, unit=None, tz=None):
if m is not None:
unit = m.groupdict()['unit']
tz = m.groupdict()['tz']
except:
except TypeError:
raise ValueError("could not construct DatetimeTZDtype")

elif isinstance(unit, compat.string_types):
Expand Down
4 changes: 2 additions & 2 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -3260,7 +3260,7 @@ def _ensure_valid_index(self, value):
if not len(self.index) and is_list_like(value):
try:
value = Series(value)
except:
except (ValueError, NotImplementedError, TypeError):
raise ValueError('Cannot set a frame with no defined index '
'and a value that cannot be converted to a '
'Series')
Expand Down Expand Up @@ -7747,7 +7747,7 @@ def convert(v):
values = np.array([convert(v) for v in values])
else:
values = convert(values)
except:
except (ValueError, TypeError):
values = convert(values)

else:
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/indexes/frozen.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ def searchsorted(self, value, side="left", sorter=None):
# xref: https://github.com/numpy/numpy/issues/5370
try:
value = self.dtype.type(value)
except:
except ValueError:
pass

return super(FrozenNDArray, self).searchsorted(
Expand Down
12 changes: 7 additions & 5 deletions pandas/core/indexes/multi.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

import numpy as np
from pandas._libs import algos as libalgos, index as libindex, lib, Timestamp
from pandas._libs import tslibs

from pandas.compat import range, zip, lrange, lzip, map
from pandas.compat.numpy import function as nv
Expand Down Expand Up @@ -1002,12 +1003,13 @@ def _try_mi(k):
return _try_mi(key)
except (KeyError):
raise
except:
except (IndexError, ValueError, TypeError):
pass

try:
return _try_mi(Timestamp(key))
except:
except (KeyError, TypeError,
IndexError, ValueError, tslibs.OutOfBoundsDatetime):
pass

raise InvalidIndexError(key)
Expand Down Expand Up @@ -1686,7 +1688,7 @@ def append(self, other):
# if all(isinstance(x, MultiIndex) for x in other):
try:
return MultiIndex.from_tuples(new_tuples, names=self.names)
except:
except (TypeError, IndexError):
return Index(new_tuples)

def argsort(self, *args, **kwargs):
Expand Down Expand Up @@ -2315,7 +2317,7 @@ def maybe_droplevels(indexer, levels, drop_level):
for i in sorted(levels, reverse=True):
try:
new_index = new_index.droplevel(i)
except:
except ValueError:

# no dropping here
return orig_index
Expand Down Expand Up @@ -2818,7 +2820,7 @@ def _convert_can_do_setop(self, other):
msg = 'other must be a MultiIndex or a list of tuples'
try:
other = MultiIndex.from_tuples(other)
except:
except TypeError:
raise TypeError(msg)
else:
result_names = self.names if self.names == other.names else None
Expand Down
6 changes: 3 additions & 3 deletions pandas/core/indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -2146,7 +2146,7 @@ def _getitem_tuple(self, tup):
self._has_valid_tuple(tup)
try:
return self._getitem_lowerdim(tup)
except:
except IndexingError:
pass

retval = self.obj
Expand Down Expand Up @@ -2705,13 +2705,13 @@ def maybe_droplevels(index, key):
for _ in key:
try:
index = index.droplevel(0)
except:
except ValueError:
# we have dropped too much, so back out
return original_index
else:
try:
index = index.droplevel(0)
except:
except ValueError:
pass

return index
Expand Down
10 changes: 5 additions & 5 deletions pandas/core/internals/blocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -666,7 +666,7 @@ def _astype(self, dtype, copy=False, errors='raise', values=None,

newb = make_block(values, placement=self.mgr_locs,
klass=klass, ndim=self.ndim)
except:
except Exception: # noqa: E722
if errors == 'raise':
raise
newb = self.copy() if copy else self
Expand Down Expand Up @@ -1142,7 +1142,7 @@ def check_int_bool(self, inplace):
# a fill na type method
try:
m = missing.clean_fill_method(method)
except:
except ValueError:
m = None

if m is not None:
Expand All @@ -1157,7 +1157,7 @@ def check_int_bool(self, inplace):
# try an interp method
try:
m = missing.clean_interp_method(method, **kwargs)
except:
except ValueError:
m = None

if m is not None:
Expand Down Expand Up @@ -2438,7 +2438,7 @@ def set(self, locs, values, check=False):
try:
if (self.values[locs] == values).all():
return
except:
except (IndexError, ValueError):
pass
try:
self.values[locs] = values
Expand Down Expand Up @@ -3172,7 +3172,7 @@ def _astype(self, dtype, copy=False, errors='raise', values=None,
def __len__(self):
try:
return self.sp_index.length
except:
except AttributeError:
return 0

def copy(self, deep=True, mgr=None):
Expand Down
5 changes: 3 additions & 2 deletions pandas/core/nanops.py
Original file line number Diff line number Diff line change
Expand Up @@ -503,7 +503,8 @@ def reduction(values, axis=None, skipna=True):
try:
result = getattr(values, meth)(axis, dtype=dtype_max)
result.fill(np.nan)
except:
except (AttributeError, TypeError,
ValueError, np.core._internal.AxisError):
result = np.nan
else:
result = getattr(values, meth)(axis)
Expand Down Expand Up @@ -815,7 +816,7 @@ def _ensure_numeric(x):
elif is_object_dtype(x):
try:
x = x.astype(np.complex128)
except:
except (TypeError, ValueError):
x = x.astype(np.float64)
else:
if not np.any(x.imag):
Expand Down
3 changes: 2 additions & 1 deletion pandas/core/ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -1545,7 +1545,8 @@ def na_op(x, y):
y = bool(y)
try:
result = libops.scalar_binop(x, y, op)
except:
except (TypeError, ValueError, AttributeError,
OverflowError, NotImplementedError):
raise TypeError("cannot compare a dtyped [{dtype}] array "
"with a scalar of type [{typ}]"
.format(dtype=x.dtype,
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/sparse/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -306,7 +306,7 @@ def __setstate__(self, state):
def __len__(self):
try:
return self.sp_index.length
except:
except AttributeError:
return 0

def __unicode__(self):
Expand Down
10 changes: 5 additions & 5 deletions pandas/core/tools/datetimes.py
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ def _convert_listlike_datetimes(arg, box, format, name=None, tz=None,
if format == '%Y%m%d':
try:
result = _attempt_YYYYMMDD(arg, errors=errors)
except:
except (ValueError, TypeError, tslibs.OutOfBoundsDatetime):
raise ValueError("cannot convert the input to "
"'%Y%m%d' date format")

Expand Down Expand Up @@ -334,7 +334,7 @@ def _adjust_to_origin(arg, origin, unit):
raise ValueError("unit must be 'D' for origin='julian'")
try:
arg = arg - j0
except:
except TypeError:
raise ValueError("incompatible 'arg' type for given "
"'origin'='julian'")

Expand Down Expand Up @@ -731,21 +731,21 @@ def calc_with_mask(carg, mask):
# try intlike / strings that are ints
try:
return calc(arg.astype(np.int64))
except:
except ValueError:
pass

# a float with actual np.nan
try:
carg = arg.astype(np.float64)
return calc_with_mask(carg, notna(carg))
except:
except ValueError:
pass

# string with NaN-like
try:
mask = ~algorithms.isin(arg, list(tslib.nat_strings))
return calc_with_mask(arg, mask)
except:
except ValueError:
pass

return None
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/window.py
Original file line number Diff line number Diff line change
Expand Up @@ -2504,7 +2504,7 @@ def _offset(window, center):
offset = (window - 1) / 2. if center else 0
try:
return int(offset)
except:
except TypeError:
return offset.astype(int)


Expand Down