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

Seaborn 0.13.1结合Pandas 2.2.0出现FutureWarning问题咨询

问题:Seaborn 0.13.1 + Pandas 2.2.0 出现FutureWarning解析

环境与代码

当前使用Seaborn 0.13.1搭配Pandas 2.2.0,运行以下代码生成直方图:

import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt
import numpy as np  # 原代码遗漏的numpy导入,补充后可正常运行

exam_scores1 = [62.58, 67.63, 81.37, 52.53, 62.98, 72.15, 59.05, 73.85, 97.24, 76.81, 89.34, 74.44, 68.52, 85.13, 90.75, 70.29, 75.62, 85.38, 77.82, 98.31, 79.08, 61.72, 71.33, 80.77, 80.31, 78.16, 61.15, 64.99, 72.67, 78.94]
exam_scores2 = [72.38, 71.28, 79.24, 83.86, 84.42, 79.38, 75.51, 76.63, 81.48,78.81,79.23,74.38,79.27,81.07,75.42,90.35,82.93,86.74,81.33,95.1,86.57,83.66,85.58,81.87,92.14,72.15,91.64,74.21,89.04,76.54,81.9,96.5,80.05,74.77,72.26,73.23,92.6,66.22,70.09,77.2]

data = np.concatenate([np.array(exam_scores1), np.array(exam_scores2)])
labels = ['1st Yr Teaching'] * len(exam_scores1) + ['2nd Yr Teaching'] * len(exam_scores2)
df = pd.DataFrame({'Score': data, 'Teaching Year': labels})

plt.figure(figsize=(10, 8))
sns.histplot(data=df, x='Score', hue=df['Teaching Year'], bins=12, kde=True, stat='density', linewidth=2)
plt.title("Final Exam Score Distribution")
plt.xlabel("Percentage")
plt.ylabel("Density")
plt.legend(title='Teaching Year')
plt.savefig('my_histogram_seaborn.png')
plt.show()

收到的警告信息

FutureWarning: When grouping with a length-1 list-like, you will need to pass a length-1 tuple to get_group in a future version of pandas. Pass (name,) instead of name to silence this warning.
data_subset = grouped_data.get_group(pd_key)


警告含义与解决方案

警告本质

这是Pandas 2.2.0的API兼容性变更导致的:当通过长度为1的列表进行数据分组时,未来版本的Pandas要求调用get_group方法必须传入长度为1的元组(比如('分组列名',)),而不能直接传单个字符串/值。Seaborn 0.13.1的内部代码还未适配这个新规则,因此触发了未来警告。

解决办法

  1. 修正hue参数写法
    把hue=df['Teaching Year']改为直接传入列名字符串hue='Teaching Year',让Seaborn内部使用更适配Pandas新规范的分组逻辑:

    sns.histplot(data=df, x='Score', hue='Teaching Year', bins=12, kde=True, stat='density', linewidth=2)
    
  2. 临时忽略警告
    如果暂时不想修改代码,可以在开头添加忽略警告的代码:

    import warnings
    warnings.filterwarnings("ignore", category=FutureWarning)
    
  3. 等待版本更新
    后续Seaborn官方会发布适配Pandas 2.2.0+的版本,升级Seaborn即可彻底解决这个问题。


内容的提问来源于stack exchange,提问作者Taharat Amin Pronoy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 17:22:49