Skip to content

Commit d554935

Browse files
author
Brendan Drury
committed
Raise ValueError instead of coercing non-numeric data to numeric types
1 parent a0ebc6e commit d554935

File tree

3 files changed

+9
-3
lines changed

3 files changed

+9
-3
lines changed

doc/source/whatsnew/v1.4.0.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -485,7 +485,7 @@ Period
485485

486486
Plotting
487487
^^^^^^^^
488-
- Fixed bug in :meth:`boxplot._grouped_plot_by_column` where trying to plot data of dtype ``object`` caused plotting to fail even if some data was numeric
488+
- When given non-numeric data, :meth:`DataFrame.boxplot` now raises a ``ValueError`` rather than a cryptic ``KeyError`` or ``ZeroDivsionError``, in line with other plotting functions like :meth:`DataFrame.hist`. (:issue:`43480`)
489489
-
490490

491491
Groupby/resample/rolling

pandas/plotting/_matplotlib/boxplot.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -390,8 +390,12 @@ def plot_group(keys, values, ax: Axes):
390390
rc = {"figure.figsize": figsize} if figsize is not None else {}
391391
with plt.rc_context(rc):
392392
ax = plt.gca()
393-
data = data.apply(pd.to_numeric, errors="ignore")
394393
data = data._get_numeric_data()
394+
naxes = len(data.columns)
395+
if naxes == 0:
396+
raise ValueError(
397+
"boxplot method requires numerical columns, nothing to plot."
398+
)
395399
if columns is None:
396400
columns = data.columns
397401
else:

pandas/tests/plotting/test_boxplot_method.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -547,7 +547,9 @@ def test_groupby_boxplot_object(self):
547547
# GH 43480
548548
df = self.hist_df.astype("object")
549549
grouped = df.groupby("gender")
550-
_check_plot_works(grouped.boxplot, subplots=False)
550+
msg = "boxplot method requires numerical columns, nothing to plot"
551+
with pytest.raises(ValueError, match=msg):
552+
_check_plot_works(grouped.boxplot, subplots=False)
551553

552554
def test_boxplot_multiindex_column(self):
553555
# GH 16748

0 commit comments

Comments
 (0)