Skip to content

Commit a5c41ae

Browse files
jbrockmendelproost
authored andcommitted
CLN: catch less in Block._astype (pandas-dev#28443)
1 parent fe50456 commit a5c41ae

File tree

1 file changed

+31
-30
lines changed

1 file changed

+31
-30
lines changed

pandas/core/internals/blocks.py

+31-30
Original file line numberDiff line numberDiff line change
@@ -600,41 +600,42 @@ def _astype(self, dtype, copy=False, errors="raise", **kwargs):
600600
return self.copy()
601601
return self
602602

603-
try:
604-
# force the copy here
605-
if self.is_extension:
606-
values = self.values.astype(dtype)
607-
else:
608-
if issubclass(dtype.type, str):
603+
# force the copy here
604+
if self.is_extension:
605+
# TODO: Should we try/except this astype?
606+
values = self.values.astype(dtype)
607+
else:
608+
if issubclass(dtype.type, str):
609609

610-
# use native type formatting for datetime/tz/timedelta
611-
if self.is_datelike:
612-
values = self.to_native_types()
613-
614-
# astype formatting
615-
else:
616-
values = self.get_values()
610+
# use native type formatting for datetime/tz/timedelta
611+
if self.is_datelike:
612+
values = self.to_native_types()
617613

614+
# astype formatting
618615
else:
619-
values = self.get_values(dtype=dtype)
620-
621-
# _astype_nansafe works fine with 1-d only
622-
vals1d = values.ravel()
623-
values = astype_nansafe(vals1d, dtype, copy=True, **kwargs)
616+
values = self.get_values()
624617

625-
# TODO(extension)
626-
# should we make this attribute?
627-
if isinstance(values, np.ndarray):
628-
values = values.reshape(self.shape)
618+
else:
619+
values = self.get_values(dtype=dtype)
629620

630-
except Exception:
631-
# e.g. astype_nansafe can fail on object-dtype of strings
632-
# trying to convert to float
633-
if errors == "raise":
634-
raise
635-
newb = self.copy() if copy else self
636-
else:
637-
newb = make_block(values, placement=self.mgr_locs, ndim=self.ndim)
621+
# _astype_nansafe works fine with 1-d only
622+
vals1d = values.ravel()
623+
try:
624+
values = astype_nansafe(vals1d, dtype, copy=True, **kwargs)
625+
except (ValueError, TypeError):
626+
# e.g. astype_nansafe can fail on object-dtype of strings
627+
# trying to convert to float
628+
if errors == "raise":
629+
raise
630+
newb = self.copy() if copy else self
631+
return newb
632+
633+
# TODO(extension)
634+
# should we make this attribute?
635+
if isinstance(values, np.ndarray):
636+
values = values.reshape(self.shape)
637+
638+
newb = make_block(values, placement=self.mgr_locs, ndim=self.ndim)
638639

639640
if newb.is_numeric and self.is_numeric:
640641
if newb.shape != self.shape:

0 commit comments

Comments
 (0)