Skip to content

dataframe.astype() exception message to include column name #48321

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

Merged
merged 12 commits into from
Oct 14, 2022
18 changes: 12 additions & 6 deletions pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -6224,12 +6224,18 @@ def astype(

results = []
for i, (col_name, col) in enumerate(self.items()):
cdt = dtype_ser.iat[i]
if isna(cdt):
res_col = col.copy() if copy else col
else:
res_col = col.astype(dtype=cdt, copy=copy, errors=errors)
results.append(res_col)
try:
cdt = dtype_ser.iat[i]
if isna(cdt):
res_col = col.copy() if copy else col
else:
res_col = col.astype(dtype=cdt, copy=copy, errors=errors)
results.append(res_col)
except Exception as ex:
ex.args = (
f"Error during type conversion for column {col_name}: {ex} ",
)
raise

elif is_extension_array_dtype(dtype) and self.ndim > 1:
# GH 18099/22869: columnwise conversion to extension dtype
Expand Down
12 changes: 12 additions & 0 deletions pandas/tests/frame/methods/test_astype.py
Original file line number Diff line number Diff line change
Expand Up @@ -490,6 +490,18 @@ def test_astype_arg_for_errors(self):

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

def test_astype_invalid_conversion(self):
# GH#47571
df = DataFrame({"a": [1, 2, "text"], "b": [1, 2, 3]})

msg = (
"Error during type conversion for column a: "
"invalid literal for int() with base 10: 'text' "
)

with pytest.raises(ValueError, match=re.escape(msg)):
df.astype({"a": int})

def test_astype_arg_for_errors_dictlist(self):
# GH#25905
df = DataFrame(
Expand Down