Jupyter Lab中pandas boxplot触发Matplotlib AssertionError问题
更新(2024/09/21)
已将pd.DataFrame.boxplot替换为pd.DataFrame.plot.box函数并重启Jupyter服务器,目前可正常重复运行,未再出现此前问题。(我认为此处仍存在bug,但无需进一步帮助。)
问题:Jupyter Lab中pandas箱线图绘制触发AssertionError
在Jupyter Lab中执行pandas箱线图绘制命令时出现如下错误:
AssertionError Traceback (most recent call last) Cell In[9], line 1 ----> 1 a2_data.boxplot(column=['MinTemp', 'MaxTemp', 'Rainfall', 'Evaporation', 'WindGustSpeed', 'WindSpeed9am', 'WindSpeed3pm', 'Humidity9am', 'Humidity3pm', 'Temp9am','Temp3pm'],rot=90); File C:\Program Files\Python312\Lib\site-packages\pandas\plotting\_core.py:533, in boxplot_frame(self, column, by, ax, fontsize, rot, grid, figsize, layout, return_type, backend, **kwargs) 516 @Substitution(data="", backend=_backend_doc) 517 @Appender(_boxplot_doc) 518 def boxplot_frame( (...) 530 **kwargs, 531 ): 532 plot_backend = _get_plot_backend(backend) --> 533 return plot_backend.boxplot_frame( 534 self, 535 column=column, 536 by=by, 537 ax=ax, 538 fontsize=fontsize, 539 rot=rot, 540 grid=grid, 541 figsize=figsize, 542 layout=layout, 543 return_type=return_type, 544 **kwargs, 545 ) File C:\Program Files\Python312\Lib\site-packages\pandas\plotting\_matplotlib\boxplot.py:492, in boxplot_frame(self, column, by, ax, fontsize, rot, grid, figsize, layout, return_type, **kwds) 477 def boxplot_frame( 478 self, 479 column=None, (...) 488 **kwds, 489 ): 490 import matplotlib.pyplot as plt --> 492 ax = boxplot( 493 self, 494 column=column, 495 by=by, 496 ax=ax, 497 fontsize=fontsize, 498 grid=grid, 499 rot=rot, 500 figsize=figsize, 501 layout=layout, 502 return_type=return_type, 503 **kwds, 504 ) 505 plt.draw_if_interactive() 506 return ax File C:\Program Files\Python312\Lib\site-packages\pandas\plotting\_matplotlib\boxplot.py:471, in boxplot(data, column, by, ax, fontsize, rot, grid, figsize, layout, return_type, **kwds) 468 else: 469 data = data[columns] --> 471 result = plot_group(columns, data.values.T, ax, **kwds) 472 ax.grid(grid) 474 return result File C:\Program Files\Python312\Lib\site-packages\pandas\plotting\_matplotlib\boxplot.py:414, in boxplot.<locals>.plot_group(keys, values, ax, **kwds) 411 ax.tick_params(axis="both", labelsize=fontsize) 413 # GH 45465: x/y are flipped when "vert" changes --> 414 _set_ticklabels( 415 ax=ax, labels=keys, is_vertical=kwds.get("vert", True), rotation=rot 416 ) 417 maybe_color_bp(bp, color_tup=colors, **kwds) 419 # Return axes in multiplot case, maybe revisit later # 985 File C:\Program Files\Python312\Lib\site-packages\pandas\plotting\_matplotlib\boxplot.py:57, in _set_ticklabels(ax, labels, is_vertical, **kwargs) 55 if len(ticks) != len(labels): 56 i, remainder = divmod(len(ticks), len(labels)) ---> 57 assert remainder == 0, remainder 58 labels *= i 59 if is_vertical: AssertionError: 3
已尝试的操作
- 多次重启Jupyter内核、电脑
- 切换Matplotlib后端为
qt5agg(无效,已改回inline)
异常表现
- 仅绘制单个列时输出空白,执行
a2_data.boxplot(column='Pressure9am')仅返回<Axes: >,无图像显示 - 其他pandas功能正常,仅Matplotlib相关的pandas绘图出现问题
- 此前该功能运行正常
执行代码片段
import pandas as pd import numpy as np a2_data = pd.read_csv("13545429.csv") a2_data.sample(10) a2_data.boxplot(column=['MinTemp', 'MaxTemp', 'Rainfall', 'Evaporation', 'WindGustSpeed', 'WindSpeed9am', 'WindSpeed3pm', 'Humidity9am', 'Humidity3pm', 'Temp9am', 'Temp3pm'],rot=90);
环境版本信息
INSTALLED VERSIONS ------------------ commit : d9cdd2ee5a58015ef6f4d15c7226110c9aab8140 python : 3.12.1.final.0 python-bits : 64 OS : Windows OS-release : 11 Version : 10.0.22631 machine : AMD64 processor : AMD64 Family 25 Model 80 Stepping 0, AuthenticAMD byteorder : little LC_ALL : None LANG : None LOCALE : English_Australia.1252 pandas : 2.2.2 numpy : 2.0.1 pytz : 2024.1 dateutil : 2.9.0.post0 setuptools : 69.0.3 pip : 24.2 Cython : None pytest : None hypothesis : None sphinx : None blosc : None feather : None xlsxwriter : None lxml.etree : None html5lib : None pymysql : None psycopg2 : None jinja2 : 3.1.4 IPython : 8.26.0 pandas_datareader : None adbc-driver-postgresql: None adbc-driver-sqlite : None bs4 : 4.12.3 bottleneck : None dataframe-api-compat : None fastparquet : None fsspec : None gcsfs : None matplotlib : 3.9.2 numba : None numexpr : None odfpy : None openpyxl : None pandas_gbq : None pyarrow : None pyreadstat : None python-calamine : None pyxlsb : None s3fs : None scipy : None sqlalchemy : None tables : None tabulate : None xarray : None xlrd : 2.0.1 zstandard : None tzdata : 2024.1 qtpy : None pyqt5 : None
原因与解决方法
该错误源于pandas箱线图绘制逻辑中的断言失败:代码假设刻度数量是标签数量的整数倍,但实际计算后余数为3,触发断言。这是pandas 2.2.2与matplotlib 3.9.2、numpy 2.0.1之间的版本兼容性bug。
有效解决方法是使用pandas推荐的新式绘图接口pd.DataFrame.plot.box替代旧的boxplot方法,修改后的代码如下:
a2_data.plot.box(column=['MinTemp', 'MaxTemp', 'Rainfall', 'Evaporation', 'WindGustSpeed', 'WindSpeed9am', 'WindSpeed3pm', 'Humidity9am', 'Humidity3pm', 'Temp9am', 'Temp3pm'], rot=90);
内容的提问来源于stack exchange,提问作者Mike C
相关产品推荐
相关产品推荐

