Skip to content

Commit 56167f0

Browse files
jbrockmendelquintusdias
authored andcommitted
CLN: one less try/except in Block methods (pandas-dev#27606)
1 parent 637a461 commit 56167f0

File tree

3 files changed

+27
-26
lines changed

3 files changed

+27
-26
lines changed

pandas/core/internals/blocks.py

+15-14
Original file line numberDiff line numberDiff line change
@@ -644,7 +644,9 @@ def _astype(self, dtype, copy=False, errors="raise", values=None, **kwargs):
644644
if isinstance(values, np.ndarray):
645645
values = values.reshape(self.shape)
646646

647-
except Exception: # noqa: E722
647+
except Exception:
648+
# e.g. astype_nansafe can fail on object-dtype of strings
649+
# trying to convert to float
648650
if errors == "raise":
649651
raise
650652
newb = self.copy() if copy else self
@@ -877,9 +879,17 @@ def setitem(self, indexer, value):
877879

878880
# coerce if block dtype can store value
879881
values = self.values
880-
try:
882+
if self._can_hold_element(value):
881883
value = self._try_coerce_args(value)
882-
except (TypeError, ValueError):
884+
885+
values = self._coerce_values(values)
886+
# can keep its own dtype
887+
if hasattr(value, "dtype") and is_dtype_equal(values.dtype, value.dtype):
888+
dtype = self.dtype
889+
else:
890+
dtype = "infer"
891+
892+
else:
883893
# current dtype cannot store value, coerce to common dtype
884894
find_dtype = False
885895

@@ -902,13 +912,6 @@ def setitem(self, indexer, value):
902912
if not is_dtype_equal(self.dtype, dtype):
903913
b = self.astype(dtype)
904914
return b.setitem(indexer, value)
905-
else:
906-
values = self._coerce_values(values)
907-
# can keep its own dtype
908-
if hasattr(value, "dtype") and is_dtype_equal(values.dtype, value.dtype):
909-
dtype = self.dtype
910-
else:
911-
dtype = "infer"
912915

913916
# value must be storeable at this moment
914917
arr_value = np.array(value)
@@ -938,7 +941,7 @@ def setitem(self, indexer, value):
938941
elif (
939942
len(arr_value.shape)
940943
and arr_value.shape[0] == values.shape[0]
941-
and np.prod(arr_value.shape) == np.prod(values.shape)
944+
and arr_value.size == values.size
942945
):
943946
values[indexer] = value
944947
try:
@@ -1134,9 +1137,7 @@ def coerce_to_target_dtype(self, other):
11341137
try:
11351138
return self.astype(dtype)
11361139
except (ValueError, TypeError, OverflowError):
1137-
pass
1138-
1139-
return self.astype(object)
1140+
return self.astype(object)
11401141

11411142
def interpolate(
11421143
self,

pandas/core/internals/construction.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -213,7 +213,7 @@ def init_dict(data, index, columns, dtype=None):
213213
arrays = Series(data, index=columns, dtype=object)
214214
data_names = arrays.index
215215

216-
missing = arrays.isnull()
216+
missing = arrays.isna()
217217
if index is None:
218218
# GH10856
219219
# raise ValueError if only scalars in dict

pandas/core/series.py

+11-11
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ def remove_na(arr):
112112
"""
113113

114114
warnings.warn(
115-
"remove_na is deprecated and is a private " "function. Do not use.",
115+
"remove_na is deprecated and is a private function. Do not use.",
116116
FutureWarning,
117117
stacklevel=2,
118118
)
@@ -127,7 +127,7 @@ def _coerce_method(converter):
127127
def wrapper(self):
128128
if len(self) == 1:
129129
return converter(self.iloc[0])
130-
raise TypeError("cannot convert the series to " "{0}".format(str(converter)))
130+
raise TypeError("cannot convert the series to {0}".format(str(converter)))
131131

132132
wrapper.__name__ = "__{name}__".format(name=converter.__name__)
133133
return wrapper
@@ -226,7 +226,7 @@ def __init__(
226226

227227
if isinstance(data, MultiIndex):
228228
raise NotImplementedError(
229-
"initializing a Series from a " "MultiIndex is not supported"
229+
"initializing a Series from a MultiIndex is not supported"
230230
)
231231
elif isinstance(data, Index):
232232
if name is None:
@@ -275,7 +275,7 @@ def __init__(
275275
pass
276276
elif isinstance(data, (set, frozenset)):
277277
raise TypeError(
278-
"{0!r} type is unordered" "".format(data.__class__.__name__)
278+
"{0!r} type is unordered".format(data.__class__.__name__)
279279
)
280280
elif isinstance(data, ABCSparseArray):
281281
# handle sparse passed here (and force conversion)
@@ -604,7 +604,7 @@ def asobject(self):
604604
*this is an internal non-public method*
605605
"""
606606
warnings.warn(
607-
"'asobject' is deprecated. Use 'astype(object)'" " instead",
607+
"'asobject' is deprecated. Use 'astype(object)' instead",
608608
FutureWarning,
609609
stacklevel=2,
610610
)
@@ -710,7 +710,7 @@ def put(self, *args, **kwargs):
710710
numpy.ndarray.put
711711
"""
712712
warnings.warn(
713-
"`put` has been deprecated and will be removed in a" "future version.",
713+
"`put` has been deprecated and will be removed in a future version.",
714714
FutureWarning,
715715
stacklevel=2,
716716
)
@@ -955,7 +955,7 @@ def real(self):
955955
.. deprecated 0.25.0
956956
"""
957957
warnings.warn(
958-
"`real` has be deprecated and will be removed in a " "future verison",
958+
"`real` has be deprecated and will be removed in a future version",
959959
FutureWarning,
960960
stacklevel=2,
961961
)
@@ -973,7 +973,7 @@ def imag(self):
973973
.. deprecated 0.25.0
974974
"""
975975
warnings.warn(
976-
"`imag` has be deprecated and will be removed in a " "future verison",
976+
"`imag` has be deprecated and will be removed in a future version",
977977
FutureWarning,
978978
stacklevel=2,
979979
)
@@ -1561,7 +1561,7 @@ def reset_index(self, level=None, drop=False, name=None, inplace=False):
15611561
).__finalize__(self)
15621562
elif inplace:
15631563
raise TypeError(
1564-
"Cannot reset_index inplace on a Series " "to create a DataFrame"
1564+
"Cannot reset_index inplace on a Series to create a DataFrame"
15651565
)
15661566
else:
15671567
df = self.to_frame(name)
@@ -1813,7 +1813,7 @@ def to_sparse(self, kind="block", fill_value=None):
18131813
"""
18141814

18151815
warnings.warn(
1816-
"Series.to_sparse is deprecated and will be removed " "in a future version",
1816+
"Series.to_sparse is deprecated and will be removed in a future version",
18171817
FutureWarning,
18181818
stacklevel=2,
18191819
)
@@ -4055,7 +4055,7 @@ def _reduce(
40554055
elif isinstance(delegate, np.ndarray):
40564056
if numeric_only:
40574057
raise NotImplementedError(
4058-
"Series.{0} does not implement " "numeric_only.".format(name)
4058+
"Series.{0} does not implement numeric_only.".format(name)
40594059
)
40604060
with np.errstate(all="ignore"):
40614061
return op(delegate, skipna=skipna, **kwds)

0 commit comments

Comments
 (0)