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

Pandas过滤数据集后Seaborn箱线图仍显示全部国家编码如何解决

问题成因

你过滤后的数据集master_venture_new中的country_code列为分类类型(Categorical),这类数据的可选取值(categories)会保留原始数据集的所有国家编码,不会因为过滤了对应行就自动删除无数据的类别。seaborn绘制箱线图时默认会展示分类列的所有预设类别,因此会出现x轴显示全部国家的问题。
如果你的数据是从Spark DataFrame转换为Pandas DataFrame得到的,Spark的StringType在特定转换配置下也会自动转为带全量类别的Pandas Categorical类型,更容易触发这个问题。

解决方法

  • 方法1:移除分类列的未使用类别
    直接删除分类列中没有对应数据的类别,后续所有绘图都会自动只保留存在的国家:
# 清理无数据的分类类别
master_venture_new['country_code'] = master_venture_new['country_code'].cat.remove_unused_categories()
# 之后正常绘图即可
sns.boxplot(x='country_code', y = 'raised_amount_usd', data = master_venture_new)
plt.show()
  • 方法2:将分类列转为普通字符串类型
    如果不需要用到分类类型的特性,直接转成字符串格式就会自动去掉预设的全量类别:
# 转为字符串类型
master_venture_new['country_code'] = master_venture_new['country_code'].astype(str)
# 之后正常绘图即可
sns.boxplot(x='country_code', y = 'raised_amount_usd', data = master_venture_new)
plt.show()
  • 方法3:绘图时强制指定x轴顺序
    不需要修改数据集,直接在绘图参数中指定你需要展示的三个国家即可:
sns.boxplot(x='country_code', y = 'raised_amount_usd', data = master_venture_new, order=['USA', 'GBR', 'IND'])
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 20:45:04