Skip to content

Commit ede9ba3

Browse files
dannyi96mroeschkephofl
authored andcommitted
dataframe.astype() exception message to include column name (pandas-dev#48321)
* dataframe.astype() exception message to include column name * added testcase * review comments * review comments * review comments * review comments * Update doc/source/whatsnew/v1.6.0.rst Co-authored-by: Matthew Roeschke <[email protected]> * dataframe.astype() exception message to include column name Co-authored-by: Matthew Roeschke <[email protected]> Co-authored-by: Patrick Hoefler <[email protected]>
1 parent eab87af commit ede9ba3

File tree

3 files changed

+20
-2
lines changed

3 files changed

+20
-2
lines changed

doc/source/whatsnew/v2.0.0.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ Other enhancements
3636
- Added ``index`` parameter to :meth:`DataFrame.to_dict` (:issue:`46398`)
3737
- Added metadata propagation for binary operators on :class:`DataFrame` (:issue:`28283`)
3838
- :class:`.CategoricalConversionWarning`, :class:`.InvalidComparison`, :class:`.InvalidVersion`, :class:`.LossySetitemError`, and :class:`.NoBufferPresent` are now exposed in ``pandas.errors`` (:issue:`27656`)
39-
-
39+
- :func:`DataFrame.astype` exception message thrown improved to include column name when type conversion is not possible. (:issue:`47571`)
4040

4141
.. ---------------------------------------------------------------------------
4242
.. _whatsnew_200.notable_bug_fixes:

pandas/core/generic.py

+7-1
Original file line numberDiff line numberDiff line change
@@ -6264,7 +6264,13 @@ def astype(
62646264
if isna(cdt):
62656265
res_col = col.copy() if copy else col
62666266
else:
6267-
res_col = col.astype(dtype=cdt, copy=copy, errors=errors)
6267+
try:
6268+
res_col = col.astype(dtype=cdt, copy=copy, errors=errors)
6269+
except ValueError as ex:
6270+
ex.args = (
6271+
f"{ex}: Error while type casting for column '{col_name}'",
6272+
)
6273+
raise
62686274
results.append(res_col)
62696275

62706276
elif is_extension_array_dtype(dtype) and self.ndim > 1:

pandas/tests/frame/methods/test_astype.py

+12
Original file line numberDiff line numberDiff line change
@@ -543,6 +543,18 @@ def test_astype_arg_for_errors(self):
543543

544544
df.astype(np.int8, errors="ignore")
545545

546+
def test_astype_invalid_conversion(self):
547+
# GH#47571
548+
df = DataFrame({"a": [1, 2, "text"], "b": [1, 2, 3]})
549+
550+
msg = (
551+
"invalid literal for int() with base 10: 'text': "
552+
"Error while type casting for column 'a'"
553+
)
554+
555+
with pytest.raises(ValueError, match=re.escape(msg)):
556+
df.astype({"a": int})
557+
546558
def test_astype_arg_for_errors_dictlist(self):
547559
# GH#25905
548560
df = DataFrame(

0 commit comments

Comments
 (0)