You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中分组箱线图无法运行的问题求助

问题:绘制Gender与Score分组箱线图时出现报错

我的数据集my_data结构如下:

Gender    Time     Money    Score

Female    23        14       26.74
Male      12        98       56.76
Male      11        34       53.98
Female    18        58       25.98

...

我想绘制Gender和Score的分组箱线图(同一图表展示两个箱线图),写了如下代码:

Males = [my_data.loc[my_data['Gender']=='Male', 'Score']]
Females = [my_data.loc[my_data['Gender']=='Female', 'Score']]

Score = [Males, Females]

fig, ax = plt.subplots()
ax.boxplot(Score)
plt.show()

运行后报错:

ValueError: X must have 2 or fewer dimensions

我尝试转成数组:

Males = np.array([my_data.loc[my_data['Gender']=='Male', 'Score']])
Females = np.array([my_data.loc[my_data['Gender']=='Female', 'Score']])

问题依旧。又试了另一种写法:

fig = plt.figure(figsize =(10, 7))
 
ax = fig.add_axes([Males, Females])
 
bp = ax.boxplot(Score)

plt.show()

这次报错:

TypeError: ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

return (<Figure size 720x504 with 0 Axes>
)

请问这是什么原因导致的?


原因分析与解决方法

第一个报错的原因

你给Males和Females额外套了一层列表,导致Score变成了三维嵌套结构(列表套列表套Series/数组),而matplotlib的boxplot函数要求输入数据的维度不超过2维,因此触发ValueError。

举个例子:

  • my_data.loc[my_data['Gender']=='Male', 'Score']本身是一维的Series/数组
  • 用[xxx]包裹后变成二维结构
  • 再将这两个二维结构放进Score = [Males, Females],就形成了三维数据,不符合函数要求

第二个报错的原因

add_axes()方法的参数必须是四元素列表,格式为[left, bottom, width, height],用来定义坐标轴在画布上的位置和尺寸。你传入的[Males, Females]是两个包含数值的数组,完全不符合参数规则,因此出现类型错误。

正确实现方式

方式1:用matplotlib原生方法

直接提取一维的Score数据,不要额外嵌套:

import matplotlib.pyplot as plt
import numpy as np

# 提取一维数据,无需外层列表包裹
males_score = my_data.loc[my_data['Gender']=='Male', 'Score'].values
females_score = my_data.loc[my_data['Gender']=='Female', 'Score'].values

# 组合成二维列表(符合boxplot要求)
score_data = [males_score, females_score]

fig, ax = plt.subplots()
ax.boxplot(score_data)
# 设置x轴标签对应分组
ax.set_xticklabels(['Male', 'Female'])
plt.show()

方式2:用pandas内置方法(更简洁)

pandas直接支持按列分组绘制箱线图,无需手动拆分数据:

import pandas as pd

my_data.boxplot(column='Score', by='Gender')
plt.show()

内容的提问来源于stack exchange,提问作者Emily Jones

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 02:01:30